pprof
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package pprof writes runtime profiling data in the format expectedby the pprof visualization tool.
Profiling a Go program¶
The first step to profiling a Go program is to enable profiling.Support for profiling benchmarks built with the standard testingpackage is built into go test. For example, the following commandruns benchmarks in the current directory and writes the CPU andmemory profiles to cpu.prof and mem.prof:
go test -cpuprofile cpu.prof -memprofile mem.prof -bench .
To add equivalent profiling support to a standalone program, addcode like the following to your main function:
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to `file`")var memprofile = flag.String("memprofile", "", "write memory profile to `file`")func main() { flag.Parse() if *cpuprofile != "" { f, err := os.Create(*cpuprofile) if err != nil { log.Fatal("could not create CPU profile: ", err) } defer f.Close() // error handling omitted for example if err := pprof.StartCPUProfile(f); err != nil { log.Fatal("could not start CPU profile: ", err) } defer pprof.StopCPUProfile() } // ... rest of the program ... if *memprofile != "" { f, err := os.Create(*memprofile) if err != nil { log.Fatal("could not create memory profile: ", err) } defer f.Close() // error handling omitted for example runtime.GC() // get up-to-date statistics // Lookup("allocs") creates a profile similar to go test -memprofile. // Alternatively, use Lookup("heap") for a profile // that has inuse_space as the default index. if err := pprof.Lookup("allocs").WriteTo(f, 0); err != nil { log.Fatal("could not write memory profile: ", err) } }}
There is also a standard HTTP interface to profiling data. Addingthe following line will install handlers under the /debug/pprof/URL to download live profiles:
import _ "net/http/pprof"
See the net/http/pprof package for more details.
Profiles can then be visualized with the pprof tool:
go tool pprof cpu.prof
There are many commands available from the pprof command line.Commonly used commands include "top", which prints a summary of thetop program hot-spots, and "web", which opens an interactive graphof hot-spots and their call graphs. Use "help" for information onall pprof commands.
For more information about pprof, seehttps://github.com/google/pprof/blob/main/doc/README.md.
Index¶
- func Do(ctx context.Context, labels LabelSet, f func(context.Context))
- func ForLabels(ctx context.Context, f func(key, value string) bool)
- func Label(ctx context.Context, key string) (string, bool)
- func SetGoroutineLabels(ctx context.Context)
- func StartCPUProfile(w io.Writer) error
- func StopCPUProfile()
- func WithLabels(ctx context.Context, labels LabelSet) context.Context
- func WriteHeapProfile(w io.Writer) error
- type LabelSet
- type Profile
- Bugs
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcDo¶added ingo1.9
Do calls f with a copy of the parent context with thegiven labels added to the parent's label map.Goroutines spawned while executing f will inherit the augmented label-set.Each key/value pair in labels is inserted into the label map in theorder provided, overriding any previous value for the same key.The augmented label map will be set for the duration of the call to fand restored once f returns.
funcForLabels¶added ingo1.9
ForLabels invokes f with each label set on the context.The function f should return true to continue iteration or false to stop iteration early.
funcLabel¶added ingo1.9
Label returns the value of the label with the given key on ctx, and a boolean indicatingwhether that label exists.
funcSetGoroutineLabels¶added ingo1.9
SetGoroutineLabels sets the current goroutine's labels to match ctx.A new goroutine inherits the labels of the goroutine that created it.This is a lower-level API thanDo, which should be used instead when possible.
funcStartCPUProfile¶
StartCPUProfile enables CPU profiling for the current process.While profiling, the profile will be buffered and written to w.StartCPUProfile returns an error if profiling is already enabled.
On Unix-like systems, StartCPUProfile does not work by default forGo code built with -buildmode=c-archive or -buildmode=c-shared.StartCPUProfile relies on the SIGPROF signal, but that signal willbe delivered to the main program's SIGPROF signal handler (if any)not to the one used by Go. To make it work, callos/signal.Notifyforsyscall.SIGPROF, but note that doing so may break any profilingbeing done by the main program.
funcStopCPUProfile¶
func StopCPUProfile()
StopCPUProfile stops the current CPU profile, if any.StopCPUProfile only returns after all the writes for theprofile have completed.
funcWithLabels¶added ingo1.9
WithLabels returns a newcontext.Context with the given labels added.A label overwrites a prior label with the same key.
Types¶
typeLabelSet¶added ingo1.9
type LabelSet struct {// contains filtered or unexported fields}
LabelSet is a set of labels.
funcLabels¶added ingo1.9
Labels takes an even number of strings representing key-value pairsand makes aLabelSet containing them.A label overwrites a prior label with the same key.Currently only the CPU and goroutine profiles utilize any labelsinformation.Seehttps://golang.org/issue/23458 for details.
typeProfile¶
type Profile struct {// contains filtered or unexported fields}
A Profile is a collection of stack traces showing the call sequencesthat led to instances of a particular event, such as allocation.Packages can create and maintain their own profiles; the most commonuse is for tracking resources that must be explicitly closed, such as filesor network connections.
A Profile's methods can be called from multiple goroutines simultaneously.
Each Profile has a unique name. A few profiles are predefined:
goroutine - stack traces of all current goroutinesheap - a sampling of memory allocations of live objectsallocs - a sampling of all past memory allocationsthreadcreate - stack traces that led to the creation of new OS threadsblock - stack traces that led to blocking on synchronization primitivesmutex - stack traces of holders of contended mutexes
These predefined profiles maintain themselves and panic on an explicitProfile.Add orProfile.Remove method call.
The CPU profile is not available as a Profile. It has a special API,theStartCPUProfile andStopCPUProfile functions, because it streamsoutput to a writer during profiling.
Heap profile¶
The heap profile reports statistics as of the most recently completedgarbage collection; it elides more recent allocation to avoid skewingthe profile away from live data and toward garbage.If there has been no garbage collection at all, the heap profile reportsall known allocations. This exception helps mainly in programs runningwithout garbage collection enabled, usually for debugging purposes.
The heap profile tracks both the allocation sites for all live objects inthe application memory and for all objects allocated since the program start.Pprof's -inuse_space, -inuse_objects, -alloc_space, and -alloc_objectsflags select which to display, defaulting to -inuse_space (live objects,scaled by size).
Allocs profile¶
The allocs profile is the same as the heap profile but changes the defaultpprof display to -alloc_space, the total number of bytes allocated sincethe program began (including garbage-collected bytes).
Block profile¶
The block profile tracks time spent blocked on synchronization primitives,such assync.Mutex,sync.RWMutex,sync.WaitGroup,sync.Cond, andchannel send/receive/select.
Stack traces correspond to the location that blocked (for example,sync.Mutex.Lock).
Sample values correspond to cumulative time spent blocked at that stacktrace, subject to time-based sampling specified byruntime.SetBlockProfileRate.
Mutex profile¶
The mutex profile tracks contention on mutexes, such assync.Mutex,sync.RWMutex, and runtime-internal locks.
Stack traces correspond to the end of the critical section causingcontention. For example, a lock held for a long time while other goroutinesare waiting to acquire the lock will report contention when the lock isfinally unlocked (that is, atsync.Mutex.Unlock).
Sample values correspond to the approximate cumulative time other goroutinesspent blocked waiting for the lock, subject to event-based samplingspecified byruntime.SetMutexProfileFraction. For example, if a callerholds a lock for 1s while 5 other goroutines are waiting for the entiresecond to acquire the lock, its unlock call stack will report 5s ofcontention.
funcNewProfile¶
NewProfile creates a new profile with the given name.If a profile with that name already exists, NewProfile panics.The convention is to use a 'import/path.' prefix to createseparate name spaces for each package.For compatibility with various tools that read pprof data,profile names should not contain spaces.
funcProfiles¶
func Profiles() []*Profile
Profiles returns a slice of all the known profiles, sorted by name.
func (*Profile)Add¶
Add adds the current execution stack to the profile, associated with value.Add stores value in an internal map, so value must be suitable for use asa map key and will not be garbage collected until the correspondingcall toProfile.Remove. Add panics if the profile already contains a stack for value.
The skip parameter has the same meaning asruntime.Caller's skipand controls where the stack trace begins. Passing skip=0 begins thetrace in the function calling Add. For example, given thisexecution stack:
Addcalled from rpc.NewClientcalled from mypkg.Runcalled from main.main
Passing skip=0 begins the stack trace at the call to Add inside rpc.NewClient.Passing skip=1 begins the stack trace at the call to NewClient inside mypkg.Run.
func (*Profile)Name¶
Name returns this profile's name, which can be passed toLookup to reobtain the profile.
func (*Profile)Remove¶
Remove removes the execution stack associated with value from the profile.It is a no-op if the value is not in the profile.
func (*Profile)WriteTo¶
WriteTo writes a pprof-formatted snapshot of the profile to w.If a write to w returns an error, WriteTo returns that error.Otherwise, WriteTo returns nil.
The debug parameter enables additional output.Passing debug=0 writes the gzip-compressed protocol buffer describedinhttps://github.com/google/pprof/tree/main/proto#overview.Passing debug=1 writes the legacy text format with commentstranslating addresses to function names and line numbers, so that aprogrammer can read the profile without tools.
The predefined profiles may assign meaning to other debug values;for example, when printing the "goroutine" profile, debug=2 means toprint the goroutine stacks in the same form that a Go program useswhen dying due to an unrecovered panic.
Notes¶
Bugs¶
Profiles are only as good as the kernel support used to generate them.Seehttps://golang.org/issue/13841 for details about known problems.