Help us shape the future of Go! Take the 2026 Go Developer Survey

profiling

package
v0.31.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

Profiling helpers

profiling provides two standard-library-only ways to inspect a Go process.

For live profiling, mount the pprof endpoints on an existing internal HTTP listener:

mux := http.NewServeMux()
profiling.Mount(mux)

Or run a dedicated diagnostics listener until a context is canceled:

go func() {
	if err := profiling.Serve(ctx, "127.0.0.1:6060"); err != nil {
		log.Printf("profiling server: %v", err)
	}
}()

Then collect a 30-second CPU profile or inspect the current heap:

go tool pprof http://127.0.0.1:6060/debug/pprof/profile?seconds=30
go tool pprof http://127.0.0.1:6060/debug/pprof/heap

For a bounded file-based session, the default captures CPU samples and a heap snapshot:

session, err := profiling.Start(profiling.DefaultConfig("./profiles"))
if err != nil {
	return err
}
defer func() {
	if err := session.Stop(); err != nil {
		log.Printf("stop profiling: %v", err)
	}
}()

Select additional runtime profiles through Config.Profiles:

cfg := profiling.DefaultConfig("./profiles")
cfg.Profiles = append(cfg.Profiles,
	profiling.AllocsProfile,
	profiling.GoroutineProfile,
	profiling.BlockProfile,
	profiling.MutexProfile,
	profiling.TraceProfile,
)
session, err := profiling.Start(cfg)

Open captured files in a browser

Use the pprof web UI for CPU, heap, allocations, goroutine, block, mutex, and thread-creation profiles:

go tool pprof -http=:0 ./profiles/20260806T120000.000000000Z-cpu.pprof
go tool pprof -http=:0 ./profiles/20260806T120000.000000000Z-heap.pprof

Replace the example path with the file written by your session. :0 selects an available local port; pprof prints the address and normally opens it in your default browser. Keep the command running while using the web interface, and press Ctrl-C when finished.

If symbol or source information is missing, provide the exact executable that created the capture as well:

go tool pprof -http=:0 ./bin/filament/worker ./profiles/my-run-cpu.pprof

Runtime traces use Go's separate trace web viewer:

go tool trace ./profiles/20260806T120000.000000000Z-trace.out

This also starts a local web server and normally opens the trace interface in your browser. Press Ctrl-C when finished.

Existing files are never overwritten; use a new prefix or remove an old capture before reusing an explicit Config.Prefix. Profiling output and live endpoints can contain sensitive process details; store files securely and expose the HTTP listener only on a trusted network. The standard net/http/pprof package registers its routes on http.DefaultServeMux when imported, so do not serve the default mux on a public listener.

Documentation

Overview

Package profiling provides drop-in helpers for live and file-based Go profiling.

Mount adds the standard /debug/pprof endpoints to an existing HTTP mux. Start records a bounded profiling session to disk. The default session records CPU activity while it is running and writes a heap snapshot when it stops:

session, err := profiling.Start(profiling.DefaultConfig("./profiles"))
if err != nil {
	return err
}
defer session.Stop()

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrActive is returned when another file-based profiling session is active.
	// The Go runtime supports only one process-wide CPU profile and trace at a time.
	ErrActive = errors.New("profiling: another session is active")
)

Functions

func Handler

func Handler() http.Handler

Handler returns an isolated handler containing only the pprof endpoints. It is useful for a dedicated diagnostics listener.

func Mount

func Mount(mux Mux)

Mount registers the standard Go pprof endpoints below /debug/pprof/.

Profiling data can expose implementation and request details. Mount these handlers only on an internal or otherwise access-controlled listener.

func Serve

func Serve(ctx context.Context, addr string) error

Serve exposes the pprof endpoints at addr until ctx is canceled. It shuts the server down gracefully and treats http.ErrServerClosed as success. Prefer a loopback or private address, for example "127.0.0.1:6060".

Types

type Config

type Config struct {
	// Directory receives the profile files and is created when necessary.
	Directory string
	// Prefix is prepended to each filename. When empty, Start uses a UTC timestamp.
	Prefix string
	// Profiles selects what to capture. At least one profile is required.
	Profiles []Profile
	// BlockRate is the average nanoseconds between sampled blocking events.
	// Zero uses 1 millisecond. It applies only when BlockProfile is selected.
	// Stop disables the process-wide block profiler because the runtime does not
	// expose its previous rate.
	BlockRate int
	// MutexFraction samples one in this many contended mutex events.
	// Zero uses 5. It applies only when MutexProfile is selected.
	MutexFraction int
	// GCBeforeHeap runs garbage collection before writing HeapProfile.
	GCBeforeHeap bool
}

Config controls a file-based profiling session.

func DefaultConfig

func DefaultConfig(directory string) Config

DefaultConfig returns a CPU and heap profiling configuration. Stop the returned Session to flush both profiles.

type Mux

type Mux interface {
	Handle(pattern string, handler http.Handler)
}

Mux is the part of http.ServeMux needed by Mount.

type Profile

type Profile string

Profile identifies a profile captured by a Session.

const (
	// CPUProfile samples CPU activity for the lifetime of the session.
	CPUProfile Profile = "cpu"
	// TraceProfile records a runtime execution trace for the lifetime of the session.
	TraceProfile Profile = "trace"
	// HeapProfile records sampled in-use memory when the session stops.
	HeapProfile Profile = "heap"
	// AllocsProfile records sampled historical allocations when the session stops.
	AllocsProfile Profile = "allocs"
	// GoroutineProfile records all current goroutine stacks when the session stops.
	GoroutineProfile Profile = "goroutine"
	// BlockProfile records blocking events over the lifetime of the session.
	BlockProfile Profile = "block"
	// MutexProfile records contended mutex events over the lifetime of the session.
	MutexProfile Profile = "mutex"
	// ThreadCreateProfile records stacks that created OS threads when the session stops.
	ThreadCreateProfile Profile = "threadcreate"
)

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session is an active file-based profiling session. A process may have only one Session at a time. Stop is safe to call more than once.

func Start

func Start(cfg Config) (*Session, error)

Start begins a file-based profiling session. CPU, trace, block, and mutex profiles collect until Stop; the other selected profiles are snapshots taken by Stop.

func (*Session) Files

func (s *Session) Files() map[Profile]string

Files returns a copy of the selected profile-to-output-path mapping.

func (*Session) Path

func (s *Session) Path(profile Profile) (string, bool)

Path returns the output path for profile and whether it was selected.

func (*Session) Stop

func (s *Session) Stop() error

Stop ends continuous profiles, writes selected snapshots, and closes all output files. Its result is cached, so repeated calls return the same error.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL