// 返回从系统中获取的字节数 funcmemConsumed()uint64 { runtime.GC() var s runtime.MemStats runtime.ReadMemStats(&s) return s.Sys //系统字节数 }
// 获取创建指定数量协程 funcmemChannel(num uint64) { var c <-chaninterface{}
var wg sync.WaitGroup noop := func() { wg.Done() <-c } wg.Add(int(num)) before := memConsumed() for i := num; i > 0; i-- { go noop() } wg.Wait() after := memConsumed() fmt.Printf("num:%d mem: %.3fMB average:%.3fkb \n", num, float64(after-before)/1024/1024, float64(after-before)/1024/float64(num))
var wg sync.WaitGroup var urls = []string{ "http://www.golang.org/", "http://www.google.com/", "http://www.somestupidname.com/", } for _, url := range urls { // Increment the WaitGroup counter. wg.Add(1) // Launch a goroutine to fetch the URL. gofunc(url string) { // Decrement the counter when the goroutine completes. defer wg.Done() // Fetch the URL. http.Get(url) }(url) } // Wait for all HTTP fetches to complete. wg.Wait()
// 一个[]byte的对象池,每个对象为一个[]byte var bytePool = sync.Pool{ New: func()interface{} { b := make([]byte, 1024) return &b }, }
funcmain() { a := time.Now().Unix() // 不使用对象池 for i := 0; i < 1000000000; i++{ obj := make([]byte,1024) _ = obj } b := time.Now().Unix() // 使用对象池 for i := 0; i < 1000000000; i++{ obj := bytePool.Get().(*[]byte) _ = obj bytePool.Put(obj) } c := time.Now().Unix() fmt.Println("without pool ", b - a, "s") fmt.Println("with pool ", c - b, "s") }