CodeBlanks Logo Icon CodeBlanks

CPU profiling

Learn to create and inspect a CPU profile.

CPU profiling

In non-HTTP programs the CPU profile is written to a file with runtime/pprof:

f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()

agirIs()

The profile takes about 100 samples per second, recording how often each function appears on the stack.

pprof commands

go tool pprof cpu.prof opens an interactive shell:

(pprof) top10        // the 10 most expensive functions
(pprof) list agirIs  // line-by-line cost
(pprof) web          // call graph

go tool pprof -http=:8081 cpu.prof opens a visual UI in the browser, including a flame graph.

Practice Profiled program

Write the CPU profile into a bytes.Buffer instead of a file with runtime/pprof: StartCPUProfile(&buf), sum 1 to 1,000,000 in a loop, StopCPUProfile(). Print the sum.

Starter code

main.go
package main

import (
    "bytes"
    "fmt"
    "runtime/pprof"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "bytes"
    "fmt"
    "runtime/pprof"
)

func main() {
    var buf bytes.Buffer
    pprof.StartCPUProfile(&buf)
    toplam := 0
    for i := 1; i <= 1000000; i++ {
        toplam += i
    }
    pprof.StopCPUProfile()
    fmt.Println(toplam)
}

Expected output

500000500000

Questions and answers

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

1 In <code>top</code> output, what is the difference between <code>flat</code> and <code>cum</code>?

  • cum is only the goroutine count
  • flat is the function's own time, cum includes what it calls Correct answer
  • flat is memory, cum is CPU
  • They are the same

Explanation: High flat means the function's own code is expensive; high cum with low flat means the cost is in the functions it calls.

2 Start the profile

Question
f, _ := os.Create("cpu.prof")
pprof.____(f)
defer pprof.StopCPUProfile()
Answer
f, _ := os.Create("cpu.prof")
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()

Explanation: StartCPUProfile starts sampling; StopCPUProfile ends it and finalizes the file.

3 pprof command

Term Meaning
top Most expensive functions
list Line-by-line cost
web Call graph
-http Browser UI

All lessons in Advanced