【问题标题】:How to profile benchmarks using the pprof tool?如何使用 pprof 工具分析基准?
【发布时间】:2023-03-20 20:35:01
【问题描述】:

我想profile我由go test -c 生成的基准,但是go tool pprof 需要一个profile 文件,通常在this 之类的主函数中生成:

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

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

【问题讨论】:

    标签: go profiling benchmarking pprof


    【解决方案1】:

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

    例如

    go test -cpuprofile cpu.out
    

    【讨论】:

    • 另外一个起初对我来说并不明显的部分是创建了一个 .test 文件供您传递给 pprof
    【解决方案2】:

    -cpuprofile 标志用于go test,如http://golang.org/cmd/go/#hdr-Description_of_testing_flags 中所述

    【讨论】:

      【解决方案3】:

      这篇文章通过一个示例解释了如何分析基准:Benchmark Profiling with 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 获取更多选项。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 2013-08-03
        • 2011-04-26
        • 2019-06-05
        • 1970-01-01
        • 2013-08-17
        相关资源
        最近更新 更多