我想要 轮廓 我的基准生成器 go test -c, ,但是 go tool pprof 需要一个通常在主函数内生成的配置文件,例如 :

func main() {
    flag.Parse()
    if *cpuprofile != "" {
        f, err := os.Create(*cpuprofile)
        if err != nil {
            log.Fatal(err)
        }
        pprof.StartCPUProfile(f)
        defer pprof.StopCPUProfile()
    }

如何在我的基准测试中创建配置文件?

有帮助吗?

解决方案

如中所述 http://golang.org/cmd/go/#hdr-Description_of_testing_flags 您可以使用标志指定配置文件 -cpuprofile.

例如

go test -cpuprofile cpu.out

其他提示

使用 -cpuprofile 标记为 go test 如记录于 http://golang.org/cmd/go/#hdr-Description_of_testing_flags

这篇文章通过一个例子解释了如何分析基准: 使用 pprof 进行基准分析.

以下基准测试模拟了一些 CPU 工作。

package main

import (
    "math/rand"
    "testing"
)

func BenchmarkRand(b *testing.B) {
    for n := 0; n < b.N; n++ {
        rand.Int63()
    }
}

要生成基准测试的 CPU 配置文件,请运行:

go test -bench=BenchmarkRand -benchmem -cpuprofile profile.out

-memprofile-blockprofile 标志可用于生成内存分配和阻塞调用配置文件。

要分析配置文件,请使用 Go 工具:

go tool pprof profile.out
(pprof) top
Showing nodes accounting for 1.16s, 100% of 1.16s total
Showing top 10 nodes out of 22
      flat  flat%   sum%        cum   cum%
     0.41s 35.34% 35.34%      0.41s 35.34%  sync.(*Mutex).Unlock
     0.37s 31.90% 67.24%      0.37s 31.90%  sync.(*Mutex).Lock
     0.12s 10.34% 77.59%      1.03s 88.79%  math/rand.(*lockedSource).Int63
     0.08s  6.90% 84.48%      0.08s  6.90%  math/rand.(*rngSource).Uint64 (inline)
     0.06s  5.17% 89.66%      1.11s 95.69%  math/rand.Int63
     0.05s  4.31% 93.97%      0.13s 11.21%  math/rand.(*rngSource).Int63
     0.04s  3.45% 97.41%      1.15s 99.14%  benchtest.BenchmarkRand
     0.02s  1.72% 99.14%      1.05s 90.52%  math/rand.(*Rand).Int63
     0.01s  0.86%   100%      0.01s  0.86%  runtime.futex
         0     0%   100%      0.01s  0.86%  runtime.allocm

这种情况下的瓶颈是互斥锁,这是由 math/rand 中的默认源同步引起的。

其他配置文件呈现和输出格式也是可能的,例如 tree. 。类型 help 以获得更多选择。

请注意,基准循环之前的任何初始化代码也将被分析。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top