问题
我有一个 go 包,带有测试套件。
当我运行此包的测试套件时,总运行时间约为 7 秒:
$ go test ./mydbpackage/ -count 1
ok mymodule/mydbpackage 7.253s
Run Code Online (Sandbox Code Playgroud)
但是,当我添加-cpuprofile=cpu.out选项时,采样不会覆盖整个运行:
$ go test ./mydbpackage/ -count 1 -cpuprofile=cpu.out
ok mymodule/mydbpackage 7.029s
$ go tool pprof -text -cum cpu.out
File: mydbpackage.test
Type: cpu
Time: Aug 6, 2020 at 9:42am (CEST)
Duration: 5.22s, Total samples = 780ms (14.95%) # <--- depending on the runs, I get 400ms to 1s
Showing nodes accounting for 780ms, 100% of 780ms total
flat flat% sum% cum cum%
0 0% 0% 440ms 56.41% testing.tRunner
10ms 1.28% 1.28% 220ms 28.21% database/sql.withLock
10ms 1.28% 2.56% 180ms 23.08% runtime.findrunnable
0 0% 2.56% 180ms 23.08% runtime.mcall
...
Run Code Online (Sandbox Code Playgroud)
查看收集的样本:
# sample from another run :
$ go tool pprof -traces cpu.out | grep "ms " # get the first line of each sample
10ms runtime.nanotime
10ms fmt.(*readRune).ReadRune
30ms syscall.Syscall
10ms runtime.scanobject
10ms runtime.gentraceback
...
# 98 samples collected, for a total sum of 1.12s
Run Code Online (Sandbox Code Playgroud)
我看到的问题是:由于某种原因,采样分析器停止收集样本,或者在某个时刻被阻止/减慢。
语境
go版本是1.14.6,平台是linux/amd64
$ go version
go version go1.14.6 linux/amd64
Run Code Online (Sandbox Code Playgroud)
该包包含与数据库交互的代码,并且测试针对实时 postgresql 服务器运行。
我尝试过的一件事是:t.Skip()内部调用,所以我用简单的;runtime.Goexit()替换了调用和变体。但这并没有改变结果。t.Skipreturn
问题
为什么不收集更多样本?我有一些已知的模式会阻止/减慢采样器的速度,或者提前终止采样器?
@Volker 在他的评论中引导我找到答案:
-cpuprofile创建一个配置文件,其中仅对主动使用 CPU 的 goroutine 进行采样。
在我的用例中:我的 go 代码花费了大量时间等待 postgresql 服务器的答案。
使用 生成跟踪go test -trace=trace.out,然后使用 提取网络阻塞配置文件,go tool trace -pprof=net trace.out > network.out产生了更多相关信息。
作为参考,除了使用 打开完整跟踪之外go tool trace trace.out,以下是您可以传递给 的值-pprof=:
- net:网络阻止配置文件
- 同步:同步阻塞配置文件
- 系统调用:系统调用阻止配置文件
- sched:调度程序延迟配置文件