CodeBlanks Logo Icon CodeBlanks

The trace tool

Learn the timeline with go tool trace.

The trace tool

pprof collects samples; go tool trace shows events on a timeline: when goroutines ran on which P, when they blocked, when GC kicked in.

f, _ := os.Create("trace.out")
trace.Start(f)
defer trace.Stop()

// code to inspect

Inspect with go tool trace trace.out, which opens a UI in the browser.

Tasks and regions

You can add your own markers to a trace, so you see units of work by name on the timeline:

ctx, task := trace.NewTask(ctx, "siparis")
defer task.End()
trace.WithRegion(ctx, "odeme", func() {
    odemeAl()
})

Trace files grow large; a few seconds of recording is usually enough.

Practice Trace recording

Start recording into a bytes.Buffer with runtime/trace, compute 10 squared inside trace.WithRegion(context.Background(), "hesap", ...) and stop recording. Print the result and buf.Len() > 0.

Starter code

main.go
package main

import (
    "bytes"
    "context"
    "fmt"
    "runtime/trace"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "bytes"
    "context"
    "fmt"
    "runtime/trace"
)

func main() {
    var buf bytes.Buffer
    trace.Start(&buf)
    sonuc := 0
    trace.WithRegion(context.Background(), "hesap", func() {
        sonuc = 10 * 10
    })
    trace.Stop()
    fmt.Println(sonuc, buf.Len() > 0)
}

Expected output

100 true

Questions and answers

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

1 For which question is trace better than pprof?

  • Which line allocates the most memory?
  • How many tests passed?
  • Why aren't my goroutines running in parallel? Correct answer
  • Which function uses the most CPU?

Explanation: Parallelism, waiting and latency problems are about time; trace visualizes them. Total-cost questions belong to pprof.

2 Start recording

Question
f, _ := os.Create("trace.out")
trace.____(f)
defer trace.Stop()
Answer
f, _ := os.Create("trace.out")
trace.Start(f)
defer trace.Stop()

Explanation: trace.Start begins recording events; trace.Stop ends it.

3 Tool and focus

Term Meaning
pprof CPU Total CPU cost
pprof heap Memory
trace Timeline
trace.WithRegion Named region

All lessons in Advanced