go / expert
Snippet
Fine-Grained Latency Profiling with runtime/trace Regions and Tasks
The standard library runtime/trace package allows developers to instrument user-level tasks, regions, and trace logs. These annotations integrate directly into execution traces generated by 'go tool trace', providing deep visibility into goroutine blocking latency, GC sweeps, and work stage durations.
snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package mainimport ("context""os""runtime/trace""time")func ProcessDataBatch(ctx context.Context, batchID int) {ctx, task := trace.NewTask(ctx, "ProcessBatch")defer task.End()trace.Log(ctx, "batchID", string(rune(batchID)))region := trace.StartRegion(ctx, "ComputeStage")time.Sleep(10 * time.Millisecond)region.End()regionIO := trace.StartRegion(ctx, "IOFlushStage")time.Sleep(15 * time.Millisecond)regionIO.End()}func main() {f, err := os.Create("trace.out")if err != nil {panic(err)}defer f.Close()if err := trace.Start(f); err != nil {panic(err)}defer trace.Stop()ProcessDataBatch(context.Background(), 42)}
Breakdown
1
ctx, task := trace.NewTask(ctx, "ProcessBatch")
Creates a logical execution unit bound to context that groups all nested child spans and log annotations in the execution tracer UI.
2
region := trace.StartRegion(ctx, "ComputeStage")
Marks the start of a high-resolution sub-interval within a task to measure exact duration of critical code blocks.