Go | 使用PGO优化编译示例

Apr 15, 2025

PGO (Profile-Guided Optimization) 是一种编译优化技术,通过收集程序的实际运行时数据来指导编译器进行更有针对性的优化。

-pgo file
        specify the file path of a profile for profile-guided optimization (PGO).
        When the special name "auto" is specified, for each main package in the
        build, the go command selects a file named "default.pgo" in the package's
        directory if that file exists, and applies it to the (transitive)
        dependencies of the main package (other packages are not affected).
        Special name "off" turns off PGO. The default is "auto".

这段说明解释了 -pgo 参数的几种用法:

  1. pgo=文件路径 - 指定一个具体的性能分析文件路径用于PGO优化
  2. pgo=auto - 自动模式(默认),会在每个main包的目录中查找名为"default.pgo"的文件
  3. pgo=off - 明确关闭PGO优化

当使用自动模式时,PGO优化只会应用到main包及其依赖项,而不会影响其他不相关的包。

收集性能分析数据

// main.go
package main

import (
    "os"
    "runtime/pprof"
)

func computeIntensive() int {
    result := 0
    for i := 0; i < 10000000; i++ {
        result += i % 10
    }
    return result
}

func main() {
    // 第一次运行时开启性能分析
    if len(os.Args) > 1 && os.Args[1] == "profile" {
        f, _ := os.Create("profile.pprof")
        defer f.Close()
        pprof.StartCPUProfile(f)
        defer pprof.StopCPUProfile()
    }
    
    // 执行计算密集型操作
    result := computeIntensive()
    println("Result:", result)
}
go build -o myapp.exe .
./myapp.exe profile

使用收集的分析数据进行优化编译

go build -pgo profile.pprof -o myapp_optimized.exe .

如果有多个pprof文件

# 使用pprof工具合并多个分析文件
go tool pprof -proto cpu1.pprof cpu2.pprof cpu3.pprof > combined.pprof
# 使用合并后的分析文件进行构建
go build -pgo combined.pprof -o myapp_optimized.exe .

测试

time ./myapp.exe
time ./myapp_optimized.exe
  • PGO 优化通常在较大、复杂的应用中效果更显著,特别是有明显热点路径的程序。对于简单程序,优化效果可能不明显,甚至因为优化开销而略微变慢。
  • PGO 主要适用于计算密集型应用。
https://inasa.dev/posts/rss.xml