allocs.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package testing
  5. import (
  6. "runtime"
  7. )
  8. // AllocsPerRun returns the average number of allocations during calls to f.
  9. // Although the return value has type float64, it will always be an integral value.
  10. //
  11. // To compute the number of allocations, the function will first be run once as
  12. // a warm-up. The average number of allocations over the specified number of
  13. // runs will then be measured and returned.
  14. //
  15. // AllocsPerRun sets GOMAXPROCS to 1 during its measurement and will restore
  16. // it before returning.
  17. func AllocsPerRun(runs int, f func()) (avg float64) {
  18. defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
  19. // Warm up the function
  20. f()
  21. // Measure the starting statistics
  22. var memstats runtime.MemStats
  23. runtime.ReadMemStats(&memstats)
  24. mallocs := 0 - memstats.Mallocs
  25. // Run the function the specified number of times
  26. for i := 0; i < runs; i++ {
  27. f()
  28. }
  29. // Read the final statistics
  30. runtime.ReadMemStats(&memstats)
  31. mallocs += memstats.Mallocs
  32. // Average the mallocs over the runs (not counting the warm-up).
  33. // We are forced to return a float64 because the API is silly, but do
  34. // the division as integers so we can ask if AllocsPerRun()==1
  35. // instead of AllocsPerRun()<2.
  36. return float64(mallocs / uint64(runs))
  37. }