capypad
0 day streak
go / expert
Snippet

Profiling Specific Logic with pprof Labels

Standard CPU profiling in Go shows where time is spent across functions, but often doesn't distinguish between different contexts (e.g., which specific user or task caused the load). pprof.Do allows you to attach key-value labels to a goroutine's context. When a CPU profile is taken, these labels are recorded, allowing you to filter the resulting profile by specific categories.

snippet.go
go
1
2
3
4
5
6
func processUserRequest(ctx context.Context, userID string) {
labels := pprof.Labels("worker", "image-processor", "user_id", userID)
pprof.Do(ctx, labels, func(ctx context.Context) {
expensiveTransformation(ctx)
})
}
Breakdown
1
pprof.Labels("worker", "image-processor", "user_id", userID)
Defines custom attributes to associate with the current execution.
2
pprof.Do(ctx, labels, func(ctx context.Context)
Wraps the function execution with the specified profiling metadata.