liveBook · Manning

Profiler

As explained in 100 Go Mistakes and How to Avoid Them

A profiler is a software tool that collects and analyzes runtime measurements such as execution time, memory use, or resource consumption of an application.

A profiler collects runtime measurements to help diagnose slow execution, lock contention, blocked goroutines, and possible memory leaks. In Go, pprof provides CPU, goroutine, heap, mutex, and block profiles. Exposing pprof does not mean CPU profiling runs continuously: it starts when requested. 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))
}

The blank import of net/http/pprof adds profiling endpoints to an HTTP server. It is a convenient way to make profiles available, including in production. section 12.8.1

Request /debug/pprof/profile to collect a CPU profile for 30 seconds by default. During collection, the profiler samples execution about every 10 ms. Use the resulting profile to find where the application spends time rather than guessing from the code. section 12.8.1

$ go tool pprof -http=:8080 <file>

Open a saved profile with go tool pprof to inspect its call graph. For a benchmark, the -cpuprofile option can save the profile first. section 12.8.1

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains profile types, HTTP activation, and CPU sampling, then shows commands for collecting and inspecting profiles.
Examples
Shows an HTTP server exposing pprof, a benchmark saving a CPU profile, and a command opening a saved profile.
What it assumes
Assumes familiarity with Go applications and HTTP handlers while demonstrating how to expose profiling endpoints.
What you can do after
Apply it via Go's pprof to collect CPU profiles and inspect where an application spends time.
How it connects
Connects CPU profiling with goroutines, heap allocation, mutex contention, synchronization blocking, and benchmarks.

Also explained in

Compare how 3 books explain profiler →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.