Go 博客

Go 1.21 中的 Profile-guided optimization (PGO)

Michael Pratt
2023 年 9 月 5 日

2023 年初,Go 1.20 发布了 profile-guided optimization (PGO) 的预览版供用户测试。在解决了预览版中的已知限制,并根据社区反馈和贡献进行了额外改进后,Go 1.21 对 PGO 的支持已准备好用于一般生产环境!请参阅profile-guided optimization (PGO) 用户指南以获取完整文档。

下文我们将通过一个使用 PGO 提升应用性能的示例。在此之前,到底什么是“profile-guided optimization (PGO)”呢?

当您构建 Go 二进制文件时,Go 编译器会执行优化,以尝试生成性能最佳的二进制文件。例如,常量传播可以在编译时评估常量表达式,避免运行时评估成本。逃逸分析可以避免为局部作用域对象分配堆空间,从而避免 GC 开销。内联将简单函数的函数体复制到调用者处,通常可以在调用者处启用进一步的优化(例如额外的常量传播或更好的逃逸分析)。解虚拟化将接口值上可以静态确定类型的间接调用转换为对具体方法的直接调用(这通常可以启用调用内联)。

Go 在各个版本中不断改进优化,但这并非易事。有些优化是可调的,但编译器不能对每种优化都“开足马力”,因为过度激进的优化实际上可能会损害性能或导致编译时间过长。其他优化则需要编译器判断函数中的“常见”路径和“不常见”路径。编译器必须根据静态启发式做出最佳猜测,因为它无法在运行时知道哪些情况会是常见的。

或者,它可以知道吗?

在没有关于代码如何在生产环境中使用的明确信息的情况下,编译器只能根据软件包的源代码进行操作。但是我们确实有一个工具可以评估生产环境的行为:性能分析 (profiling)。如果我们向编译器提供性能分析数据,它可以做出更明智的决策:更积极地优化最常用的函数,或更准确地选择常见情况。

利用应用行为的性能分析数据进行编译器优化被称为 Profile-Guided Optimization (PGO)(也称为 Feedback-Directed Optimization (FDO),反馈导向优化)。

示例

我们来构建一个将 Markdown 转换为 HTML 的服务:用户将 Markdown 源文件上传到 /render,服务返回 HTML 转换结果。我们可以轻松使用 gitlab.com/golang-commonmark/markdown 来实现这一点。

设置

$ go mod init example.com/markdown
$ go get gitlab.com/golang-commonmark/markdown@bf3e522c626a

main.go

package main

import (
    "bytes"
    "io"
    "log"
    "net/http"
    _ "net/http/pprof"

    "gitlab.com/golang-commonmark/markdown"
)

func render(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Only POST allowed", http.StatusMethodNotAllowed)
        return
    }

    src, err := io.ReadAll(r.Body)
    if err != nil {
        log.Printf("error reading body: %v", err)
        http.Error(w, "Internal Server Error", http.StatusInternalServerError)
        return
    }

    md := markdown.New(
        markdown.XHTMLOutput(true),
        markdown.Typographer(true),
        markdown.Linkify(true),
        markdown.Tables(true),
    )

    var buf bytes.Buffer
    if err := md.Render(&buf, src); err != nil {
        log.Printf("error converting markdown: %v", err)
        http.Error(w, "Malformed markdown", http.StatusBadRequest)
        return
    }

    if _, err := io.Copy(w, &buf); err != nil {
        log.Printf("error writing response: %v", err)
        http.Error(w, "Internal Server Error", http.StatusInternalServerError)
        return
    }
}

func main() {
    http.HandleFunc("/render", render)
    log.Printf("Serving on port 8080...")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

构建并运行服务器

$ go build -o markdown.nopgo.exe
$ ./markdown.nopgo.exe
2023/08/23 03:55:51 Serving on port 8080...

我们尝试从另一个终端发送一些 Markdown。我们可以使用 Go 项目中的 README.md 作为示例文档

$ curl -o README.md -L "https://raw.githubusercontent.com/golang/go/c16c2c49e2fa98ae551fc6335215fadd62d33542/README.md"
$ curl --data-binary @README.md http://localhost:8080/render
<h1>The Go Programming Language</h1>
<p>Go is an open source programming language that makes it easy to build simple,
reliable, and efficient software.</p>
...

性能分析

现在我们有一个正在运行的服务了,我们来收集性能分析数据并使用 PGO 进行重新构建,看看能否获得更好的性能。

main.go 中,我们导入了 net/http/pprof,它会自动向服务器添加一个 /debug/pprof/profile 端点,用于获取 CPU 性能分析数据。

通常,您会希望从生产环境中收集性能分析数据,以便编译器获得生产环境中行为的代表性视图。由于本示例没有“生产”环境,我创建了一个简单程序来在收集性能分析数据时生成负载。获取并启动负载生成器(确保服务器仍在运行!)

$ go run github.com/prattmic/markdown-pgo/load@latest

在它运行时,从服务器下载性能分析数据

$ curl -o cpu.pprof "http://localhost:8080/debug/pprof/profile?seconds=30"

完成后,停止负载生成器和服务器。

使用性能分析数据

当 Go 工具链在主包目录中找到名为 default.pgo 的性能分析文件时,它会自动启用 PGO。或者,go build 命令的 -pgo 标志可以指定用于 PGO 的性能分析文件的路径。

我们建议将 default.pgo 文件提交到您的仓库。将性能分析文件与源代码一起存储可确保用户只需通过获取仓库(无论是通过版本控制系统还是通过 go get)即可自动访问该文件,并且构建过程保持可复现性。

我们来构建

$ mv cpu.pprof default.pgo
$ go build -o markdown.withpgo.exe

我们可以使用 go version 检查构建中是否启用了 PGO

$ go version -m markdown.withpgo.exe
./markdown.withpgo.exe: go1.21.0
...
        build   -pgo=/tmp/pgo121/default.pgo

评估

我们将使用 Go benchmark 版本的负载生成器来评估 PGO 对性能的影响。

首先,我们将对未启用 PGO 的服务器进行基准测试。启动该服务器

$ ./markdown.nopgo.exe

在它运行时,运行几次基准测试迭代

$ go get github.com/prattmic/markdown-pgo@latest
$ go test github.com/prattmic/markdown-pgo/load -bench=. -count=40 -source $(pwd)/README.md > nopgo.txt

完成后,停止原始服务器并启动启用了 PGO 的版本

$ ./markdown.withpgo.exe

在它运行时,运行几次基准测试迭代

$ go test github.com/prattmic/markdown-pgo/load -bench=. -count=40 -source $(pwd)/README.md > withpgo.txt

完成后,我们来比较结果

$ go install golang.org/x/perf/cmd/benchstat@latest
$ benchstat nopgo.txt withpgo.txt
goos: linux
goarch: amd64
pkg: github.com/prattmic/markdown-pgo/load
cpu: Intel(R) Xeon(R) W-2135 CPU @ 3.70GHz
        │  nopgo.txt  │            withpgo.txt             │
        │   sec/op    │   sec/op     vs base               │
Load-12   374.5µ ± 1%   360.2µ ± 0%  -3.83% (p=0.000 n=40)

新版本速度提升了大约 3.8%!在 Go 1.21 中,通过启用 PGO,工作负载通常可以获得 2% 到 7% 的 CPU 使用率提升。性能分析数据包含大量关于应用行为的信息,Go 1.21 刚刚开始利用这些信息进行有限的优化。未来的版本将随着编译器更多部分利用 PGO 而继续提升性能。

下一步

在本例中,收集性能分析数据后,我们使用与原始构建中完全相同的源代码重新构建了服务器。在实际场景中,总是有持续的开发。因此,我们可能会从生产环境(运行的是上周的代码)收集性能分析数据,并用它来构建今天的源代码。这完全没问题!Go 中的 PGO 可以处理源代码的微小更改而不会出现问题。当然,随着时间的推移,源代码会偏离得越来越多,因此仍然需要偶尔更新性能分析数据。

有关使用 PGO、最佳实践和注意事项的更多信息,请参阅 profile-guided optimization (PGO) 用户指南。如果您对幕后发生的事情感到好奇,请继续阅读!

幕后原理

为了更好地理解是什么让这个应用更快,我们来看一下幕后原理,看看性能是如何改变的。我们将研究两种不同的 PGO 驱动优化。

内联

为了观察内联带来的改进,我们来分析一下启用和未启用 PGO 的 Markdown 应用。

我将使用一种称为差分性能分析(differential profiling)的技术进行比较,该技术会收集两个性能分析文件(一个启用 PGO,一个未启用)并进行比较。对于差分性能分析,重要的是两个文件代表相同数量的工作,而不是相同的时间,因此我调整了服务器使其自动收集性能分析数据,并调整了负载生成器使其发送固定数量的请求然后退出服务器。

我对服务器进行的更改以及收集的性能分析文件可在 https://github.com/prattmic/markdown-pgo 找到。负载生成器运行时使用了 -count=300000 -quit 参数。

作为快速一致性检查,我们来看一下处理所有 30 万个请求所需的总 CPU 时间

$ go tool pprof -top cpu.nopgo.pprof | grep "Total samples"
Duration: 116.92s, Total samples = 118.73s (101.55%)
$ go tool pprof -top cpu.withpgo.pprof | grep "Total samples"
Duration: 113.91s, Total samples = 115.03s (100.99%)

CPU 时间从约 118 秒降至约 115 秒,下降了约 3%。这与我们的基准测试结果一致,是一个好迹象,表明这些性能分析文件具有代表性。

现在我们可以打开一个差分性能分析文件来寻找节省之处

$ go tool pprof -diff_base cpu.nopgo.pprof cpu.withpgo.pprof
File: markdown.profile.withpgo.exe
Type: cpu
Time: Aug 28, 2023 at 10:26pm (EDT)
Duration: 230.82s, Total samples = 118.73s (51.44%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top -cum
Showing nodes accounting for -0.10s, 0.084% of 118.73s total
Dropped 268 nodes (cum <= 0.59s)
Showing top 10 nodes out of 668
      flat  flat%   sum%        cum   cum%
    -0.03s 0.025% 0.025%     -2.56s  2.16%  gitlab.com/golang-commonmark/markdown.ruleLinkify
     0.04s 0.034% 0.0084%     -2.19s  1.84%  net/http.(*conn).serve
     0.02s 0.017% 0.025%     -1.82s  1.53%  gitlab.com/golang-commonmark/markdown.(*Markdown).Render
     0.02s 0.017% 0.042%     -1.80s  1.52%  gitlab.com/golang-commonmark/markdown.(*Markdown).Parse
    -0.03s 0.025% 0.017%     -1.71s  1.44%  runtime.mallocgc
    -0.07s 0.059% 0.042%     -1.62s  1.36%  net/http.(*ServeMux).ServeHTTP
     0.04s 0.034% 0.0084%     -1.58s  1.33%  net/http.serverHandler.ServeHTTP
    -0.01s 0.0084% 0.017%     -1.57s  1.32%  main.render
     0.01s 0.0084% 0.0084%     -1.56s  1.31%  net/http.HandlerFunc.ServeHTTP
    -0.09s 0.076% 0.084%     -1.25s  1.05%  runtime.newobject
(pprof) top
Showing nodes accounting for -1.41s, 1.19% of 118.73s total
Dropped 268 nodes (cum <= 0.59s)
Showing top 10 nodes out of 668
      flat  flat%   sum%        cum   cum%
    -0.46s  0.39%  0.39%     -0.91s  0.77%  runtime.scanobject
    -0.40s  0.34%  0.72%     -0.40s  0.34%  runtime.nextFreeFast (inline)
     0.36s   0.3%  0.42%      0.36s   0.3%  gitlab.com/golang-commonmark/markdown.performReplacements
    -0.35s  0.29%  0.72%     -0.37s  0.31%  runtime.writeHeapBits.flush
     0.32s  0.27%  0.45%      0.67s  0.56%  gitlab.com/golang-commonmark/markdown.ruleReplacements
    -0.31s  0.26%  0.71%     -0.29s  0.24%  runtime.writeHeapBits.write
    -0.30s  0.25%  0.96%     -0.37s  0.31%  runtime.deductAssistCredit
     0.29s  0.24%  0.72%      0.10s 0.084%  gitlab.com/golang-commonmark/markdown.ruleText
    -0.29s  0.24%  0.96%     -0.29s  0.24%  runtime.(*mspan).base (inline)
    -0.27s  0.23%  1.19%     -0.42s  0.35%  bytes.(*Buffer).WriteRune

当指定 pprof -diff_base 时,pprof 中显示的值是两个性能分析文件之间的差值。例如,runtime.scanobject 在启用 PGO 后比未启用时少了 0.46 秒的 CPU 时间。另一方面,gitlab.com/golang-commonmark/markdown.performReplacements 多使用了 0.36 秒的 CPU 时间。在差分性能分析中,我们通常关注绝对值(flatcum 列),因为百分比没有意义。

top -cum 显示按累积变化排序的最大差异。也就是说,一个函数及其所有传递调用的函数在 CPU 时间上的差异。这通常会显示程序调用图中最外层的帧,例如 main 或其他 goroutine 入口点。在这里,我们可以看到大部分节省来自处理 HTTP 请求的 ruleLinkify 部分。

top 显示仅限于函数本身变化的顶层差异。这通常会显示程序调用图中的内部帧,这是实际工作大部分发生的地方。在这里,我们可以看到单独的节省主要来自 runtime 函数。

那些是什么?我们来看一下调用栈,看看它们来自哪里

(pprof) peek scanobject$
Showing nodes accounting for -3.72s, 3.13% of 118.73s total
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context
----------------------------------------------------------+-------------
                                            -0.86s 94.51% |   runtime.gcDrain
                                            -0.09s  9.89% |   runtime.gcDrainN
                                             0.04s  4.40% |   runtime.markrootSpans
    -0.46s  0.39%  0.39%     -0.91s  0.77%                | runtime.scanobject
                                            -0.19s 20.88% |   runtime.greyobject
                                            -0.13s 14.29% |   runtime.heapBits.nextFast (inline)
                                            -0.08s  8.79% |   runtime.heapBits.next
                                            -0.08s  8.79% |   runtime.spanOfUnchecked (inline)
                                             0.04s  4.40% |   runtime.heapBitsForAddr
                                            -0.01s  1.10% |   runtime.findObject
----------------------------------------------------------+-------------
(pprof) peek gcDrain$
Showing nodes accounting for -3.72s, 3.13% of 118.73s total
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context
----------------------------------------------------------+-------------
                                               -1s   100% |   runtime.gcBgMarkWorker.func2
     0.15s  0.13%  0.13%        -1s  0.84%                | runtime.gcDrain
                                            -0.86s 86.00% |   runtime.scanobject
                                            -0.18s 18.00% |   runtime.(*gcWork).balance
                                            -0.11s 11.00% |   runtime.(*gcWork).tryGet
                                             0.09s  9.00% |   runtime.pollWork
                                            -0.03s  3.00% |   runtime.(*gcWork).tryGetFast (inline)
                                            -0.03s  3.00% |   runtime.markroot
                                            -0.02s  2.00% |   runtime.wbBufFlush
                                             0.01s  1.00% |   runtime/internal/atomic.(*Bool).Load (inline)
                                            -0.01s  1.00% |   runtime.gcFlushBgCredit
                                            -0.01s  1.00% |   runtime/internal/atomic.(*Int64).Add (inline)
----------------------------------------------------------+-------------

所以 runtime.scanobject 最终来自 runtime.gcBgMarkWorkerGo GC 指南告诉我们 runtime.gcBgMarkWorker 是垃圾收集器的一部分,因此 runtime.scanobject 的节省肯定是 GC 节省。那 nextFreeFast 和其他 runtime 函数呢?

(pprof) peek nextFreeFast$
Showing nodes accounting for -3.72s, 3.13% of 118.73s total
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context
----------------------------------------------------------+-------------
                                            -0.40s   100% |   runtime.mallocgc (inline)
    -0.40s  0.34%  0.34%     -0.40s  0.34%                | runtime.nextFreeFast
----------------------------------------------------------+-------------
(pprof) peek writeHeapBits
Showing nodes accounting for -3.72s, 3.13% of 118.73s total
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context
----------------------------------------------------------+-------------
                                            -0.37s   100% |   runtime.heapBitsSetType
                                                 0     0% |   runtime.(*mspan).initHeapBits
    -0.35s  0.29%  0.29%     -0.37s  0.31%                | runtime.writeHeapBits.flush
                                            -0.02s  5.41% |   runtime.arenaIndex (inline)
----------------------------------------------------------+-------------
                                            -0.29s   100% |   runtime.heapBitsSetType
    -0.31s  0.26%  0.56%     -0.29s  0.24%                | runtime.writeHeapBits.write
                                             0.02s  6.90% |   runtime.arenaIndex (inline)
----------------------------------------------------------+-------------
(pprof) peek heapBitsSetType$
Showing nodes accounting for -3.72s, 3.13% of 118.73s total
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context
----------------------------------------------------------+-------------
                                            -0.82s   100% |   runtime.mallocgc
    -0.12s   0.1%   0.1%     -0.82s  0.69%                | runtime.heapBitsSetType
                                            -0.37s 45.12% |   runtime.writeHeapBits.flush
                                            -0.29s 35.37% |   runtime.writeHeapBits.write
                                            -0.03s  3.66% |   runtime.readUintptr (inline)
                                            -0.01s  1.22% |   runtime.writeHeapBitsForAddr (inline)
----------------------------------------------------------+-------------
(pprof) peek deductAssistCredit$
Showing nodes accounting for -3.72s, 3.13% of 118.73s total
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context
----------------------------------------------------------+-------------
                                            -0.37s   100% |   runtime.mallocgc
    -0.30s  0.25%  0.25%     -0.37s  0.31%                | runtime.deductAssistCredit
                                            -0.07s 18.92% |   runtime.gcAssistAlloc
----------------------------------------------------------+-------------

看起来 nextFreeFast 和前 10 名中的其他一些最终来自 runtime.mallocgc,GC 指南告诉我们这是内存分配器。

GC 和分配器中成本降低意味着我们总体上分配的内存更少。我们来看一下堆性能分析数据以获取洞察

$ go tool pprof -sample_index=alloc_objects -diff_base heap.nopgo.pprof heap.withpgo.pprof
File: markdown.profile.withpgo.exe
Type: alloc_objects
Time: Aug 28, 2023 at 10:28pm (EDT)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
Showing nodes accounting for -12044903, 8.29% of 145309950 total
Dropped 60 nodes (cum <= 726549)
Showing top 10 nodes out of 58
      flat  flat%   sum%        cum   cum%
  -4974135  3.42%  3.42%   -4974135  3.42%  gitlab.com/golang-commonmark/mdurl.Parse
  -4249044  2.92%  6.35%   -4249044  2.92%  gitlab.com/golang-commonmark/mdurl.(*URL).String
   -901135  0.62%  6.97%    -977596  0.67%  gitlab.com/golang-commonmark/puny.mapLabels
   -653998  0.45%  7.42%    -482491  0.33%  gitlab.com/golang-commonmark/markdown.(*StateInline).PushPending
   -557073  0.38%  7.80%    -557073  0.38%  gitlab.com/golang-commonmark/linkify.Links
   -557073  0.38%  8.18%    -557073  0.38%  strings.genSplit
   -436919   0.3%  8.48%    -232152  0.16%  gitlab.com/golang-commonmark/markdown.(*StateBlock).Lines
   -408617  0.28%  8.77%    -408617  0.28%  net/textproto.readMIMEHeader
    401432  0.28%  8.49%     499610  0.34%  bytes.(*Buffer).grow
    291659   0.2%  8.29%     291659   0.2%  bytes.(*Buffer).String (inline)

-sample_index=alloc_objects 选项向我们显示了分配的计数,无论大小如何。这很有用,因为我们正在调查 CPU 使用率的下降,这通常与分配计数而不是大小更相关。这里有很多减少,但我们重点关注最大的减少项 mdurl.Parse

作为参考,我们来看一下未启用 PGO 时此函数的总分配计数

$ go tool pprof -sample_index=alloc_objects -top heap.nopgo.pprof | grep mdurl.Parse
   4974135  3.42% 68.60%    4974135  3.42%  gitlab.com/golang-commonmark/mdurl.Parse

之前的总计数为 4974135,这意味着 mdurl.Parse 已消除了 100% 的分配!

回到差分性能分析,我们收集更多背景信息

(pprof) peek mdurl.Parse
Showing nodes accounting for -12257184, 8.44% of 145309950 total
----------------------------------------------------------+-------------
      flat  flat%   sum%        cum   cum%   calls calls% + context
----------------------------------------------------------+-------------
                                          -2956806 59.44% |   gitlab.com/golang-commonmark/markdown.normalizeLink
                                          -2017329 40.56% |   gitlab.com/golang-commonmark/markdown.normalizeLinkText
  -4974135  3.42%  3.42%   -4974135  3.42%                | gitlab.com/golang-commonmark/mdurl.Parse
----------------------------------------------------------+-------------

mdurl.Parse 的调用来自 markdown.normalizeLinkmarkdown.normalizeLinkText

(pprof) list mdurl.Parse
Total: 145309950
ROUTINE ======================== gitlab.com/golang-commonmark/mdurl.Parse in /usr/local/google/home/mpratt/go/pkg/mod/gitlab.com/golang-commonmark/mdurl@v0.0.0-20191124015652-932350d1cb84/parse
.go
  -4974135   -4974135 (flat, cum)  3.42% of Total
         .          .     60:func Parse(rawurl string) (*URL, error) {
         .          .     61:   n, err := findScheme(rawurl)
         .          .     62:   if err != nil {
         .          .     63:           return nil, err
         .          .     64:   }
         .          .     65:
  -4974135   -4974135     66:   var url URL
         .          .     67:   rest := rawurl
         .          .     68:   hostless := false
         .          .     69:   if n > 0 {
         .          .     70:           url.RawScheme = rest[:n]
         .          .     71:           url.Scheme, rest = strings.ToLower(rest[:n]), rest[n+1:]

这些函数及其调用者的完整源代码可在以下位置找到

那么这里发生了什么?在未启用 PGO 的构建中,mdurl.Parse 被认为过大而不符合内联条件。然而,由于我们的 PGO 性能分析文件表明对这个函数的调用很“热”(hot),编译器确实对其进行了内联。我们可以从性能分析文件中的“(inline)”注解看到这一点

$ go tool pprof -top cpu.nopgo.pprof | grep mdurl.Parse
     0.36s   0.3% 63.76%      2.75s  2.32%  gitlab.com/golang-commonmark/mdurl.Parse
$ go tool pprof -top cpu.withpgo.pprof | grep mdurl.Parse
     0.55s  0.48% 58.12%      2.03s  1.76%  gitlab.com/golang-commonmark/mdurl.Parse (inline)

mdurl.Parse 在第 66 行(var url URL)创建一个局部变量 URL,然后在第 145 行(return &url, nil)返回该变量的指针。通常这需要将该变量分配在堆上,因为它的引用在函数返回后仍然存在。然而,一旦 mdurl.Parse 被内联到 markdown.normalizeLink 中,编译器就可以观察到该变量没有逃逸出 normalizeLink,从而允许编译器将其分配在栈上。markdown.normalizeLinkTextmarkdown.normalizeLink 类似。

性能分析中显示的第二大减少,来自 mdurl.(*URL).String,也是内联后消除逃逸的类似情况。

在这些情况下,我们通过减少堆分配提高了性能。PGO 和一般编译器优化的一部分强大之处在于,对分配的影响根本不是编译器 PGO 实现的一部分。PGO 唯一做的更改是允许内联这些“热”函数调用。所有对逃逸分析和堆分配的影响都是适用于任何构建的标准优化。改进的逃逸行为是内联带来的一个很好的下游效应,但它不是唯一的效果。许多优化都可以利用内联。例如,当某些输入是常量时,常量传播可能能够在内联后简化函数中的代码。

解虚拟化

除了上面示例中看到的内联之外,PGO 还可以驱动接口调用的条件解虚拟化。

在讨论 PGO 驱动的解虚拟化之前,让我们后退一步,总体定义一下“解虚拟化”。假设您有类似这样的代码

f, _ := os.Open("foo.txt")
var r io.Reader = f
r.Read(b)

这里我们调用了 io.Reader 接口的 Read 方法。由于接口可以有多种实现,编译器会生成一个间接函数调用,这意味着它会在运行时从接口值中的类型查找要调用的正确方法。与直接调用相比,间接调用会产生一些额外的运行时成本,但更重要的是它们会阻止某些编译器优化。例如,编译器无法对间接调用执行逃逸分析,因为它不知道具体的方法实现。

但在上面的示例中,我们确实知道具体的方法实现。它一定是 os.(*File).Read,因为 *os.File 是唯一可能被赋值给 r 的类型。在这种情况下,编译器会执行解虚拟化,将对 io.Reader.Read 的间接调用替换为对 os.(*File).Read 的直接调用,从而允许其他优化。

(您可能在想“这段代码没用,谁会这么写?”这是个好问题,但请注意,上面的代码可能是内联的结果。假设 f 被传递给一个接受 io.Reader 参数的函数。一旦函数被内联,现在 io.Reader 就变得具体了。)

PGO 驱动的解虚拟化将此概念扩展到具体类型无法静态已知的情况,但性能分析可以表明,例如,io.Reader.Read 调用在大多数时候都指向 os.(*File).Read。在这种情况下,PGO 可以将 r.Read(b) 替换为类似以下的代码

if f, ok := r.(*os.File); ok {
    f.Read(b)
} else {
    r.Read(b)
}

也就是说,我们添加一个运行时检查来判断最有可能出现的具体类型,如果是,则使用具体调用,否则回退到标准的间接调用。这样做的好处是,常见路径(使用 *os.File)可以被内联并应用额外的优化,但我们仍然保留一个回退路径,因为性能分析结果并不能保证总是这种情况。

在我们对 Markdown 服务器的分析中,我们没有看到 PGO 驱动的解虚拟化,但我们也只查看了受影响最大的区域。PGO(以及大多数编译器优化)通常是通过在许多不同地方进行非常小的改进来累积获得收益的,因此可能发生的事情比我们看到的要多。

内联和解虚拟化是 Go 1.21 中可用的两种 PGO 驱动优化,但正如我们所见,它们通常会开启额外的优化。此外,未来的 Go 版本将继续通过额外的优化来改进 PGO。

致谢

将 profile-guided optimization 添加到 Go 是一项团队努力,我特别想感谢 Uber 的 Raj Barik 和 Jin Lin,以及 Google 的 Cherry Mui 和 Austin Clements 的贡献。这种跨社区协作是 Go 变得优秀的关键部分。

下一篇文章:为不断发展的 Go 生态系统扩展 gopls
上一篇文章:完美可复现、可验证的 Go 工具链
博客索引