go benchmark 中 allocs/op 和 B/op 是什么意思?

问题描述 投票:0回答:2

当我使用

go test -v -bench=. -benchmem
运行基准测试时,我看到以下结果。

f1     10000        120860 ns/op        2433 B/op         28 allocs/op
f2     10000        120288 ns/op        2288 B/op         26 allocs/op

根据我的理解:

  1. 10000
    是迭代次数
    for i := 0; i < b.N; i++ {
  2. XXX ns/op
    是完成一次迭代所需的大致时间

但即使在阅读文档之后,我也无法找出

B/op
allocs/op
的含义。


我的猜测是allocs/op与垃圾收集和内存分配有关(越少越好)。

任何人都可以对这些值的含义给出一个很好的解释。另外,很高兴知道为什么要执行上升步骤和主要步骤来减少它们(我意识到这是特定于测试的,但可能有一些在许多情况下有效的通用提示)

go benchmarking
2个回答
67
投票

allocs/op
表示每个操作发生了多少个不同的内存分配(单次迭代)。

B/op
是每个操作分配了多少字节。


0
投票

快速挖掘“testing/benchmark.go”源代码,表明:

// AllocsPerOp returns the "allocs/op" metric,
// which is calculated as r.MemAllocs / r.N.
func (r BenchmarkResult) AllocsPerOp() int64

那么 r.MemAllocs 是什么?

type BenchmarkResult struct {
    MemAllocs uint64        // The total number of memory allocations.
    MemBytes  uint64        // The total number of bytes allocated.
    // ...
}

“总数”是如何累计的?

// file: testing/allocs.go

func AllocsPerRun(runs int, f func()) (avg float64) {
    // ...

    // Measure the starting statistics
    var memstats runtime.MemStats
    runtime.ReadMemStats(&memstats)
    mallocs := 0 - memstats.Mallocs

    // Run the function the specified number of times
    for i := 0; i < runs; i++ {
        f()
    }

    // Read the final statistics
    runtime.ReadMemStats(&memstats)
    mallocs += memstats.Mallocs

    // ...
    return float64(mallocs / uint64(runs))

现在我们知道无论什么是runtime.Memstats.Mallocs,都是“alloc/ops”中的“alloc”。这是内存状态:

// file: runtime.mstats.go

type MemStats struct {
    // ...
    // Mallocs is the cumulative count of heap objects allocated.
    // The number of live objects is Mallocs - Frees.
    Mallocs uint64
    // ...
}
© www.soinside.com 2019 - 2024. All rights reserved.