🎓 A1Learner
🔍
0 of 28 lessons completed

Go Profiling

Profiling is measuring where a program uses time and memory while it runs. The net/http/pprof package adds profile pages to a web server, and its index page lives at /debug/pprof/.

The profile index page answers

A recorder takes the place of a client and sends a request to /debug/pprof/ on the default server. The printed code is the status of the answer.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	_ "net/http/pprof"
)

func main() {
	req := httptest.NewRequest(http.MethodGet, "/debug/pprof/", nil)
	rec := httptest.NewRecorder()
	http.DefaultServeMux.ServeHTTP(rec, req)
	fmt.Println("Status:", rec.Code)
}

The heap page answers

The heap profile has its own path under the same root. The same request shape asks for /debug/pprof/heap.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	_ "net/http/pprof"
)

func main() {
	req := httptest.NewRequest(http.MethodGet, "/debug/pprof/heap", nil)
	rec := httptest.NewRecorder()
	http.DefaultServeMux.ServeHTTP(rec, req)
	fmt.Println("Status:", rec.Code)
}

Three pages checked in a loop

A loop asks for the index, heap, and goroutine pages in turn. Each answer code goes into a slot, and the codes print in path order.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	_ "net/http/pprof"
)

func main() {
	paths := []string{"/debug/pprof/", "/debug/pprof/heap", "/debug/pprof/goroutine"}
	codes := make([]int, len(paths))
	for i, path := range paths {
		req := httptest.NewRequest(http.MethodGet, path, nil)
		rec := httptest.NewRecorder()
		http.DefaultServeMux.ServeHTTP(rec, req)
		codes[i] = rec.Code
	}
	fmt.Println(codes[0], codes[1], codes[2])
}

Example

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	_ "net/http/pprof"
)

func check(path string) int {
	req := httptest.NewRequest(http.MethodGet, path, nil)
	rec := httptest.NewRecorder()
	http.DefaultServeMux.ServeHTTP(rec, req)
	return rec.Code
}

func main() {
	fmt.Println("Index:", check("/debug/pprof/"))
	fmt.Println("Heap:", check("/debug/pprof/heap"))
}

Key points

  • Importing net/http/pprof with the blank identifier adds profile pages to the default web server.
  • The index page at /debug/pprof/ lists the profiles the server can give.
  • The heap profile at /debug/pprof/heap reports the memory a program holds.
  • In real use, run the server on your own machine and open the profile page in a browser.
  • The go tool pprof command reads a profile and shows where time or memory went.
  • The command go test -cpuprofile saves a CPU profile while the tests run.

In this example, a small checker function sends one request and returns its status code. Main asks for the index page and then the heap page. Both lines print 200, so both pages are served.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Go Playground

Exercise

What does a status code of 200 from /debug/pprof/heap show?