如何等待垃圾回收完成?

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

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:(还请注意那里的注释)

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()
    . . .

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:

确定