Skip to content

Instantly share code, notes, and snippets.

@wrfly
Last active February 20, 2018 14:06
Show Gist options
  • Save wrfly/7de7f1e0c87860aa2f92dc6ed64cb75b to your computer and use it in GitHub Desktop.
Save wrfly/7de7f1e0c87860aa2f92dc6ed64cb75b to your computer and use it in GitHub Desktop.
syncPool_mem_usage_test
package main
import (
"fmt"
"os"
"runtime/pprof"
"sync"
"sync/atomic"
"time"
)
var wg sync.WaitGroup
var newMake uint64
var reused uint64
var alloc int = 1e4
var bufPool = sync.Pool{
New: func() interface{} {
atomic.AddUint64(&newMake, 1)
return make([]byte, 1e6)
},
}
func main() {
wg.Add(alloc)
for i := 0; i < alloc; i++ {
go func(num int) {
// justMake()
// bufPoolGet()
bufPoolGetAndPut(num)
// bufPoolSleepAndGetAndPut(num)
wg.Done()
}(i)
}
wg.Wait()
// runtime.GC()
// debug.FreeOSMemory()
f, _ := os.Create("mem.porf")
pprof.WriteHeapProfile(f)
nm := newMake
re := reused
reSlice := [][]byte{}
for i := 0; i < alloc; i++ {
b := bufPool.Get()
buf := b.([]byte)
if buf[0] != 0 {
fmt.Printf("reuse %s", buf)
reSlice = append(reSlice, buf)
}
}
println("newmake:", nm)
println("reused:", re)
println("reused slice(maybe equal to newmake) len:", len(reSlice))
}
func justMake() {
buf := make([]byte, 1e6)
atomic.AddUint64(&newMake, 1)
if buf == nil {
panic("never")
}
}
func bufPoolGet(num ...int) []byte {
buf := bufPool.Get()
b := buf.([]byte)
if b[0] != 0 {
atomic.AddUint64(&reused, 1)
} else {
b = []byte(fmt.Sprintln(num))
}
return b
}
func bufPoolGetAndPut(num int) {
b := bufPoolGet(num)
bufPool.Put(b)
}
func bufPoolSleepAndGetAndPut(num int) {
s := time.Duration(time.Now().UnixNano() % 5)
time.Sleep(time.Millisecond * s)
bufPoolGetAndPut(num)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment