You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
106 lines
2.1 KiB
Go
106 lines
2.1 KiB
Go
package test
|
|
|
|
import (
|
|
"context"
|
|
"joybuywork/internal/repository/cache"
|
|
"joybuywork/internal/repository/finder"
|
|
"runtime"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func TestFinder(t *testing.T) {
|
|
|
|
t.Run("func", func(t *testing.T) {
|
|
|
|
var m1, m2 runtime.MemStats
|
|
|
|
runtime.ReadMemStats(&m1)
|
|
|
|
data, _ := cache.NewProject(context.Background()).FindById(143)
|
|
|
|
t.Logf("%+v", data)
|
|
|
|
runtime.ReadMemStats(&m2)
|
|
|
|
t.Logf("Alloc: %v B, TotalAlloc: %v B, HeapAlloc: %v B",
|
|
m2.Alloc-m1.Alloc,
|
|
m2.TotalAlloc-m1.TotalAlloc,
|
|
m2.HeapAlloc-m1.HeapAlloc)
|
|
})
|
|
|
|
t.Run("call", func(t *testing.T) {
|
|
var m1, m2 runtime.MemStats
|
|
|
|
runtime.ReadMemStats(&m1)
|
|
|
|
data, _ := finder.Project(context.Background(), int64(143))
|
|
|
|
t.Logf("%+v", data)
|
|
|
|
runtime.ReadMemStats(&m2)
|
|
|
|
t.Logf("Alloc: %v, TotalAlloc: %v, HeapAlloc: %v",
|
|
m2.Alloc-m1.Alloc,
|
|
m2.TotalAlloc-m1.TotalAlloc,
|
|
m2.HeapAlloc-m1.HeapAlloc)
|
|
})
|
|
|
|
var ms runtime.MemStats
|
|
runtime.ReadMemStats(&ms)
|
|
t.Logf("堆内存: %d MiB, map size: %d MiB, 总申请:%d Mib\n", ms.Alloc/1024/1024, ms.Sys/1024/1024, ms.TotalAlloc/1024/1024)
|
|
t.Run("wait", func(t *testing.T) {
|
|
|
|
go func() {
|
|
t1 := time.NewTicker(time.Second)
|
|
for {
|
|
select {
|
|
case <-t1.C:
|
|
|
|
wg := sync.WaitGroup{}
|
|
for i := 0; i < 10; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
cache.NewProject(context.Background()).FindById(143)
|
|
|
|
}()
|
|
}
|
|
|
|
wg.Wait()
|
|
}
|
|
}
|
|
}()
|
|
|
|
})
|
|
|
|
t.Run("wait2", func(t *testing.T) {
|
|
t2 := time.NewTicker(time.Second)
|
|
for {
|
|
select {
|
|
case <-t2.C:
|
|
runtime.ReadMemStats(&ms)
|
|
t.Logf("堆内存: %d MiB, map size: %d MiB, 总申请:%d Mib\n", ms.Alloc/1024/1024, ms.Sys/1024/1024, ms.TotalAlloc/1024/1024)
|
|
}
|
|
}
|
|
})
|
|
|
|
}
|
|
|
|
func TestAllocations(t *testing.T) {
|
|
allocs := testing.AllocsPerRun(100, func() {
|
|
finder.Project(context.Background(), 143)
|
|
})
|
|
if allocs > 0 {
|
|
t.Errorf("代码发生了 %v 次内存分配", allocs)
|
|
}
|
|
}
|
|
|
|
func BenchmarkSomething(b *testing.B) {
|
|
b.ReportAllocs() // 报告内存分配情况
|
|
for i := 0; i < b.N; i++ {
|
|
finder.Project(context.Background(), int64(143))
|
|
}
|
|
}
|