golang 性能测试

在 Go 语言中,CPU Profiling(CPU 性能剖析) 是分析程序 CPU 使用情况、定位性能瓶颈的核心手段。Go 内置了强劲的 pprof 工具支持,可通过标准库 runtime/pprof 或 net/http/pprof 实现。

✅ 对命令行程序(main 程序)进行 CPU Profiling

步骤 1:在代码中启用 profiling

// file: main.go
package main

import (
    "os"
    "runtime/pprof"
    "time"
)

func heavyWork() {
    // 模拟高 CPU 消耗
    total := 0
    for i := 0; i < 1e9; i++ {
       total += i
    }
    _ = total
}

func main() {
    // 创建 CPU profile 文件
    f, err := os.Create("cpu.prof")
    if err != nil {
       panic(err)
    }
    defer f.Close()

    // 开始 CPU profiling
    if err := pprof.StartCPUProfile(f); err != nil {
       panic(err)
    }
    defer pprof.StopCPUProfile()

    // 执行你要分析的代码
    heavyWork()
    time.Sleep(60 * time.Second)
}

步骤 2:运行程序

go run main.go
# 生成 cpu.prof 文件

步骤 3:使用 pprof 分析

go tool pprof cpu.prof

进入交互式界面后,常用命令:

命令

说明

top

显示消耗 CPU 最多的函数

list 函数名

查看该函数的源码及每行耗时

web

生成调用图(需安装 Graphviz)

svg

/ pdf

导出图形报告

示例输出:

(pprof) top
Showing nodes accounting for 150ms, 100% of 150ms total
Showing top 10 nodes out of 26
flat flat% sum% cum cum%
130ms 86.67% 86.67% 140ms 93.33% main.heavyWork (inline)
10ms 6.67% 93.33% 10ms 6.67% runtime.asyncPreempt
10ms 6.67% 100% 10ms 6.67% runtime.cgocall
0 0% 100% 10ms 6.67% internal/syscall/windows/registry.Key.GetMUIStringValue
0 0% 100% 10ms 6.67% internal/syscall/windows/registry.regLoadMUIString
0 0% 100% 140ms 93.33% main.main
0 0% 100% 140ms 93.33% runtime.main
0 0% 100% 10ms 6.67% runtime.syscall_syscalln
0 0% 100% 10ms 6.67% runtime/pprof.(*profileBuilder).readMapping
0 0% 100% 10ms 6.67% runtime/pprof.newProfileBuilder
(pprof) list heavyWork
Total: 150ms
ROUTINE ======================== main.heavyWork in C:golanglianxicpuprofcpuprof.go
130ms 140ms (flat, cum) 93.33% of Total
. . 10:func heavyWork() {
. . 11: // 模拟高 CPU 消耗
. . 12: total := 0
130ms 140ms 13: for i := 0; i < 1e9; i++ {
. . 14: total += i
. . 15: }
. . 16: _ = total
. . 17:}
. . 18:

高级技巧

1. 只分析特定时间段

通过 StartCPUProfile / StopCPUProfile 包裹关键代码段,避免全局开销。

2. 比较两个版本的性能(diff)

go tool pprof -base old.prof new.prof

3. 查看火焰图(Flame Graph)

需额外工具(如 go-torch 或新版 pprof 支持):

go tool pprof -http=:8080 cpu.prof

然后浏览器打开 http://localhost:8080,点击 View → Flame Graph

提示:确保已安装 Graphviz(sudo apt install graphviz 或 brew install graphviz)

注意事项

  • CPU profiling 本身有轻微开销(约 2~5%),生产环境谨慎开启。
  • 不要将 /debug/pprof 暴露在公网!应在内网或加鉴权。
  • 对于短生命周期程序(<100ms),可能采样不足,提议延长运行时间。
© 版权声明

相关文章

暂无评论

none
暂无评论...