英文:
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 byBenchmarkUnlimited
)
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
:(还请注意那里的注释)
func (b *B) runN(n int) {
benchmarkLock.Lock()
defer benchmarkLock.Unlock()
defer b.runCleanup(normalPanic)
// 通过清除之前运行的垃圾,尝试为每次运行获取可比较的环境。
runtime.GC() // <========== 这里
b.raceErrors = -race.Errors()
b.N = n
b.parallelism = 1
b.ResetTimer()
b.StartTimer()
b.benchFunc(b)
b.StopTimer()
. . .
}
英文:
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)
func (b *B) runN(n int) {
benchmarkLock.Lock()
defer benchmarkLock.Unlock()
defer b.runCleanup(normalPanic)
// Try to get a comparable environment for each run
// by clearing garbage from previous runs.
runtime.GC() // <========== HERE
b.raceErrors = -race.Errors()
b.N = n
b.parallelism = 1
b.ResetTimer()
b.StartTimer()
b.benchFunc(b)
b.StopTimer()
. . .
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论