如何等待垃圾回收完成?

huangapple go评论109阅读模式
英文:

How to wait for garbage collection to complete?

问题

我想知道是否有一种方法可以等待垃圾回收完成?

假设我正在运行基准测试:

  • BenchmarkUnlimited(执行大量工作)
  • BenchmarkNumCPU(受到BenchmarkUnlimited的影响)

问题在于BenchmarkUnlimited会创建大量的分配内存,垃圾回收需要时间,但BenchmarkNumCPU已经在运行,其结果可能会受到前一个基准测试的影响。

是否有一种方法可以告诉Go程序在运行下一个基准测试之前等待垃圾回收完成?

英文:

I was wondering is there a way to wait for GC to finish?

Lets say I'm running benchmarks:

  • BenchmarkUnlimited (Does a lot of work)
  • BenchmarkNumCPU (Is affected by BenchmarkUnlimited)

The problem here is that BenchmarkUnlimited creates a lot of allocations, garbage collecting all of this takes time, but BenchmarkNumCPU is already running and its results can be affected by the previous benchmark.

Is there a way to tell the go program to wait for the GC to complete before running the next benchmark?

答案1

得分: 4

Go基准测试框架在运行每个基准测试之前已经调用了runtime.GC()函数。

因此,没有问题 - 你可以放心,每个基准测试都是在没有前一个基准测试垃圾的情况下开始的。

请参考go/src/testing/benchmark.go:(还请注意那里的注释)

  1. func (b *B) runN(n int) {
  2. benchmarkLock.Lock()
  3. defer benchmarkLock.Unlock()
  4. defer b.runCleanup(normalPanic)
  5. // 通过清除之前运行的垃圾,尝试为每次运行获取可比较的环境。
  6. runtime.GC() // <========== 这里
  7. b.raceErrors = -race.Errors()
  8. b.N = n
  9. b.parallelism = 1
  10. b.ResetTimer()
  11. b.StartTimer()
  12. b.benchFunc(b)
  13. b.StopTimer()
  14. . . .
  15. }
英文:

The Go benchmark framework already invokes runtime.GC() before running each benchmark.

So there is no issue - you can rest assured each benchmark is started free of garbage from previous benchmarks.

See go/src/testing/benchmark.go: (also notice the comment there)

  1. func (b *B) runN(n int) {
  2. benchmarkLock.Lock()
  3. defer benchmarkLock.Unlock()
  4. defer b.runCleanup(normalPanic)
  5. // Try to get a comparable environment for each run
  6. // by clearing garbage from previous runs.
  7. runtime.GC() // <========== HERE
  8. b.raceErrors = -race.Errors()
  9. b.N = n
  10. b.parallelism = 1
  11. b.ResetTimer()
  12. b.StartTimer()
  13. b.benchFunc(b)
  14. b.StopTimer()
  15. . . .

huangapple
  • 本文由 发表于 2021年9月3日 17:47:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/69042889.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定