golang benchmark 测试
main.go
package main import ( // "sync" ) //// A dummy struct //type Person struct { // Name string //} // //// Initializing pool //var personPool = sync.Pool{ // // New optionally specifies a function to generate // // a value when Get would otherwise return nil. // New: func() interface{} { return new(Person) }, //} // Main function func main() { // Get hold of an instance //newPerson := personPool.Get().(*Person) //// Defer release function //// After that the same instance is //// reusable by another routine //defer personPool.Put(newPerson) //// Using the instance //newPerson.Name = "Jack" }
main_test.go
package main import ( "testing" "sync" ) type Person struct { Age int } var personPool = sync.Pool{ New: func() interface{} { return new(Person) }, } func BenchmarkWithoutPool(b *testing.B) { var p *Person b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { for j := 0; j < 10000; j++ { p = new(Person) p.Age = 23 } } } func BenchmarkWithPool(b *testing.B) { var p *Person b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { for j := 0; j < 10000; j++ { p = personPool.Get().(*Person) p.Age = 23 personPool.Put(p) } } }
go test -cpu 1,2,8 -bench=.