Optimizing by guesswork can miss the actual bottleneck. Profiling measures what a Go application is doing so you can investigate CPU use, memory use, contention, blocked goroutines, or a possible leak before changing code. section 12.8 section 12.8.1
Choose a profile for the question at hand:
- CPU: Where does the application spend execution time? section 12.8.1
- Heap: What is allocated, and does current memory usage suggest a leak? section 12.8.1
- Goroutine: What are ongoing goroutines doing? section 12.8.1
- Mutex or block: Where is execution delayed by locks or synchronization? section 12.8.1
A common mistake is to treat a CPU profile as a continuous record of every operation. Go’s CPU profiler samples execution: by default, it interrupts the application every 10 ms, collects activity, then lets execution resume. Requesting `/debug/pprof/profile` starts a 30-second CPU profile by default. Profiling that affects performance is activated for a specific period rather than running continuously. section 12.8.1
package main
import (
"fmt"
"log"
"net/http"
_ "net/http/pprof" #1
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { #2
fmt.Fprintf(w, "")
})
log.Fatal(http.ListenAndServe(":80", nil))
}
This Go server imports `net/http/pprof` for its side effect, exposing profiling data under `/debug/pprof`. section 12.8.1
$ go test -bench=. -cpuprofile profile.out
For a benchmark, this command writes a CPU profile to `profile.out`; it offers another way to collect evidence before optimizing. section 12.8.1
$ go tool pprof -http=:8080 <file>
Open a collected profile with `go tool pprof` to inspect where execution or resource use is concentrated. section 12.8.1
A goroutine that has not made progress
A goroutine profile can expose a stack trace showing a goroutine waiting on a channel receive for 1,420 minutes. That is a concrete place to investigate; the stack trace alone does not establish why it is waiting. section 12.8.1
Use the execution tracer when the question is how goroutines are scheduled rather than which functions dominate a CPU profile. CPU profiling is sampled and per function; traces show per-goroutine execution without the CPU profiler’s sampling-rate limit. User-defined tasks can add finer boundaries to a trace. section 12.8.2










