diff --git a/internal/ttlcache/cache_test.go b/internal/ttlcache/cache_test.go index 9e5c1dc..df01e24 100644 --- a/internal/ttlcache/cache_test.go +++ b/internal/ttlcache/cache_test.go @@ -1,6 +1,7 @@ package ttlcache import ( + "github.com/TeaOSLab/EdgeNode/internal/utils/testutils" "github.com/iwind/TeaGo/rands" "runtime" "strconv" @@ -29,19 +30,26 @@ func TestNewCache(t *testing.T) { } func TestCache_Memory(t *testing.T) { - var stat1 = &runtime.MemStats{} - runtime.ReadMemStats(stat1) + testutils.StartMemoryStats(t) - cache := NewCache() - for i := 0; i < 10_000_000; i++ { + var cache = NewCache() + var count = 2_000_000 + for i := 0; i < count; i++ { cache.Write("a"+strconv.Itoa(i), 1, time.Now().Unix()+3600) } - t.Log("waiting ...") - var stat2 = &runtime.MemStats{} - runtime.ReadMemStats(stat2) + t.Log(cache.Count()) - t.Log((stat2.HeapInuse-stat1.HeapInuse)/1024/1024, "MB") + time.Sleep(1 * time.Second) + for i := 0; i < count; i++ { + if i%2 == 0 { + cache.Delete("a" + strconv.Itoa(i)) + } + } + + t.Log(cache.Count()) + + cache.Count() } func BenchmarkCache_Add(b *testing.B) { diff --git a/internal/ttlcache/piece.go b/internal/ttlcache/piece.go index 6370c9f..1871adb 100644 --- a/internal/ttlcache/piece.go +++ b/internal/ttlcache/piece.go @@ -10,7 +10,8 @@ import ( type Piece struct { m map[uint64]*Item maxItems int - locker sync.RWMutex + + locker sync.RWMutex } func NewPiece(maxItems int) *Piece { diff --git a/internal/utils/testutils/memory.go b/internal/utils/testutils/memory.go new file mode 100644 index 0000000..da864fa --- /dev/null +++ b/internal/utils/testutils/memory.go @@ -0,0 +1,33 @@ +// Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved. + +package testutils + +import ( + "fmt" + timeutil "github.com/iwind/TeaGo/utils/time" + "runtime" + "testing" + "time" +) + +func StartMemoryStats(t *testing.T) { + var ticker = time.NewTicker(1 * time.Second) + go func() { + var stat = &runtime.MemStats{} + var lastHeapInUse uint64 + + for range ticker.C { + runtime.ReadMemStats(stat) + if stat.HeapInuse == lastHeapInUse { + return + } + lastHeapInUse = stat.HeapInuse + + var before = time.Now() + runtime.GC() + var cost = time.Since(before).Seconds() + + t.Log(timeutil.Format("H:i:s"), "HeapInuse:", fmt.Sprintf("%.2fM", float64(stat.HeapInuse)/1024/1024), "NumGC:", stat.NumGC, "Cost:", fmt.Sprintf("%.4f", cost*1000), "ms") + } + }() +}