CodeBlanks Logo Icon CodeBlanks

Summary - pprof

Combine CPU and memory profiles to write an analysis.

Profiling summary

The order of performance work: measure → find the biggest cost → change → measure again. The tools:

  • net/http/pprof or runtime/pprof: CPU and heap profiles.
  • go test -bench -cpuprofile -memprofile: repeatable measurement.
  • go tool trace: timing and parallelism.
  • runtime.ReadMemStats: a quick memory reading.

PGO: profile-guided optimization

Since Go 1.21 a CPU profile taken from production can be given to the compiler. It inlines hot functions more aggressively; typical gains are 2–14%.

cp cpu.prof default.pgo   // into the main package folder
go build                   // default.pgo is used automatically

Practice Before/after measurement

Compare two ways of joining with testing.AllocsPerRun: one with s += "x" in a loop, the other with strings.Builder (with Grow(100)). Print both allocation counts for 100 items on one line.

Starter code

main.go
package main

import (
    "fmt"
    "strings"
    "testing"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "strings"
    "testing"
)

var sink string

func main() {
    a := testing.AllocsPerRun(10, func() {
        s := ""
        for i := 0; i < 100; i++ {
            s += "x"
        }
        sink = s
    })
    b := testing.AllocsPerRun(10, func() {
        var sb strings.Builder
        sb.Grow(100)
        for i := 0; i < 100; i++ {
            sb.WriteString("x")
        }
        sink = sb.String()
    })
    fmt.Println(a > b, b)
}

Expected output

true 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 If a function uses 2% of total CPU, what does making it 10× faster gain?

  • Nothing can be measured
  • At most about 2% Correct answer
  • 20%
  • The program becomes 10× faster

Explanation: The gain is limited by the function's share of the total (Amdahl's law); focus on the largest shares first.

2 PGO file

Question
cp cpu.prof ____
go build
Answer
cp cpu.prof default.pgo
go build

Explanation: default.pgo in the main package folder is read automatically by go build.

3 Group summary

Term Meaning
pprof Where is it spent?
trace When does it happen?
-benchmem Allocation count
default.pgo Profile-guided build

All lessons in Advanced