routine

测算在 goroutine 创建之前和之后分配的内存数量

  1. package main
  2. import (
  3. "fmt"
  4. "runtime"
  5. "sync"
  6. )
  7. func main() {
  8. memConsumed := func() uint64 {
  9. runtime.GC()
  10. var s runtime.MemStats
  11. runtime.ReadMemStats(&s)
  12. return s.Sys
  13. }
  14. var c <-chan interface{}
  15. var wg sync.WaitGroup
  16. noop := func() {
  17. wg.Done()
  18. <-c
  19. }
  20. const numGoroutines = 1e5
  21. wg.Add(numGoroutines)
  22. before := memConsumed()
  23. for i := numGoroutines; i > 0; i-- {
  24. fmt.Println("go noop()", i)
  25. go noop()
  26. }
  27. wg.Wait()
  28. after := memConsumed()
  29. fmt.Printf("%.3fkb", float64(after-before)/numGoroutines/1000)
  30. }