CodeBlanks Logo Icon CodeBlanks

What is pprof?

Learn the basics of the pprof profiling tool.

What is pprof?

pprof is Go's profiling tool that shows where a program spends its time and memory. It lets you measure instead of guess. It is added to an HTTP service with one line:

import _ "net/http/pprof"

go http.ListenAndServe("localhost:6060", nil)

Then go tool pprof http://localhost:6060/debug/pprof/profile?seconds=30 takes a 30-second CPU profile.

Profile types

There are several profiles under /debug/pprof/: profile (CPU), heap (memory), goroutine (all goroutine stacks), block and mutex (waiting points), allocs (all allocations). The goroutine profile is very handy for finding leaked goroutines.

Practice Goroutine count

runtime.NumGoroutine() returns the number of running goroutines. Start three goroutines (each waiting on <-dur), print the count, then call close(dur).

Starter code

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime"
)

func main() {
    dur := make(chan struct{})
    for i := 0; i < 3; i++ {
        go func() { <-dur }()
    }
    fmt.Println(runtime.NumGoroutine())
    close(dur)
}

Expected output

4

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why bind the pprof endpoint to <code>localhost</code>?

  • pprof doesn't work on other addresses
  • To avoid port conflicts
  • Profile data exposes internals; it shouldn't be public Correct answer
  • So it runs faster

Explanation: Profiles reveal function names, stacks and hints about memory contents; taking a profile also loads the server.

2 Add pprof

Question
import _ "net/http/____"
Answer
import _ "net/http/pprof"

Explanation: Importing net/http/pprof registers the /debug/pprof/ endpoints on the default mux.

3 Profile and question

Term Meaning
profile Where is CPU spent?
heap Where is memory held?
goroutine Which goroutines exist?
mutex Where is lock waiting?

All lessons in Advanced