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=.

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章