CPU Profiling
Start with CPU Profiling
In this lesson, explore cpu profiling through one small Go program, and connect its output to the language rules behind it.
What you’ll learn
- Explain the main purpose of cpu profiling.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
CPU profiling samples which functions consume processor time. Run benchmarks with -cpuprofile or call runtime/pprof.StartCPUProfile in a suitable environment.
Use go tool pprof to inspect measured hotspots; a hotspot identifies where time went, not automatically what change is correct.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Try go test -run ^$ -bench . -cpuprofile cpu.out in a package with benchmarks, then go tool pprof cpu.out. For pprof help, see Profiling Go Programs.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func compute() int {
total := 0
for i := 1; i <= 1000; i++ {
total += i * i
}
return total
}
func main() { fmt.Println("Computed:", compute()) }
Output
Computed: 333833500Trace what the program does
compute performs deterministic CPU work and prints its result. A CPU profile of a suitably repeated workload can identify where sampled CPU time accumulates.
Avoid common mistakes
- Too-short runs can yield uninformative profiles.
- A profile from a synthetic loop is not evidence about production load.
Try it yourself
Benchmark compute and write a CPU profile, then locate the most expensive function in pprof.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced CPU Profiling in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.