优化代码

This commit is contained in:
GoEdgeLab
2022-08-07 11:12:29 +08:00
parent ca339a090c
commit 37486eba8c
7 changed files with 87 additions and 126 deletions

View File

@@ -1,37 +1,16 @@
package utils
import (
"github.com/iwind/TeaGo/assert"
"runtime"
"sync"
"testing"
)
func TestNewBytePool(t *testing.T) {
a := assert.NewAssertion(t)
pool := NewBytePool(5, 8)
buf := pool.Get()
a.IsTrue(len(buf) == 8)
a.IsTrue(len(pool.c) == 0)
pool.Put(buf)
a.IsTrue(len(pool.c) == 1)
pool.Get()
a.IsTrue(len(pool.c) == 0)
for i := 0; i < 10; i++ {
pool.Put(buf)
}
t.Log(len(pool.c))
a.IsTrue(len(pool.c) == 5)
}
func TestBytePool_Memory(t *testing.T) {
var stat1 = &runtime.MemStats{}
runtime.ReadMemStats(stat1)
var pool = NewBytePool(20480, 32*1024)
var pool = NewBytePool(32 * 1024)
for i := 0; i < 20480; i++ {
pool.Put(make([]byte, 32*1024))
}
@@ -44,18 +23,50 @@ func TestBytePool_Memory(t *testing.T) {
var stat2 = &runtime.MemStats{}
runtime.ReadMemStats(stat2)
t.Log((stat2.HeapInuse-stat1.HeapInuse)/1024/1024, "MB,", pool.Size(), "slices")
t.Log((stat2.HeapInuse-stat1.HeapInuse)/1024/1024, "MB,")
}
func BenchmarkBytePool_Get(b *testing.B) {
runtime.GOMAXPROCS(1)
pool := NewBytePool(1024, 1)
var pool = NewBytePool(1)
b.ResetTimer()
for i := 0; i < b.N; i++ {
buf := pool.Get()
var buf = pool.Get()
_ = buf
pool.Put(buf)
}
b.Log(pool.Size())
}
func BenchmarkBytePool_Get_Parallel(b *testing.B) {
runtime.GOMAXPROCS(1)
var pool = NewBytePool(1024)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
var buf = pool.Get()
pool.Put(buf)
}
})
}
func BenchmarkBytePool_Get_Sync(b *testing.B) {
runtime.GOMAXPROCS(1)
var pool = &sync.Pool{
New: func() any {
return make([]byte, 1024)
},
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
var buf = pool.Get()
pool.Put(buf)
}
})
}