Lab 02: Profiling with pprof

Time: 45 minutes | Level: Advanced | Docker: docker run -it --rm golang:1.22-alpine sh

Overview

Master Go's profiling tools: CPU profiling, heap profiling, goroutine analysis, and the net/http/pprof HTTP endpoint. Learn to benchmark with testing.B and analyze profiles with go tool pprof.


Step 1: CPU Profiling with runtime/pprof

// cpu_profile.go
package main

import (
	"os"
	"runtime/pprof"
	"math"
	"fmt"
)

func expensiveComputation(n int) float64 {
	result := 0.0
	for i := 0; i < n; i++ {
		result += math.Sqrt(float64(i)) * math.Sin(float64(i))
	}
	return result
}

func main() {
	// Start CPU profile
	f, _ := os.Create("cpu.prof")
	defer f.Close()
	pprof.StartCPUProfile(f)
	defer pprof.StopCPUProfile()

	// Do work
	result := expensiveComputation(10_000_000)
	fmt.Printf("Result: %.4f\n", result)
}

Step 2: Heap Profiling


Step 3: HTTP pprof Endpoint

💡 The /debug/pprof/ routes are registered automatically when you import net/http/pprof with a blank identifier. Never expose this endpoint publicly — it leaks internals.


Step 4: Benchmarks with Profiling


Step 5: Goroutine Profile


Step 6: Allocs Profile


Step 7: go tool pprof Interactive Mode

💡 Use -http=:8080 to launch the pprof web UI with flame graphs: go tool pprof -http=:8080 cpu.prof


Step 8: Capstone — Full Profiling Workflow

Run the full workflow:

📸 Verified Output:


Summary

Tool
Command
Purpose

CPU Profile

pprof.StartCPUProfile(f)

Find CPU hotspots

Heap Profile

pprof.WriteHeapProfile(f)

Find memory usage

Goroutine Profile

pprof.Lookup("goroutine")

Find goroutine leaks

HTTP pprof

import _ "net/http/pprof"

Live server profiling

Benchmark + profile

go test -bench -cpuprofile

Measure + profile together

Analysis

go tool pprof -top file.prof

Analyze profiles

Key Takeaways:

  • CPU profiles sample goroutine stacks at 100Hz by default

  • Heap profiles show in-use allocations at snapshot time

  • Always use -benchmem to see allocation counts

  • go tool pprof -http=:8080 provides an interactive flame graph UI

Last updated