How to profile Go applications for performance?
Aug 02, 2025 am 02:33 AMImport net/http/pprof for web apps to enable profiling endpoints like /debug/pprof/profile and /debug/pprof/heap. 2. Use go tool pprof to collect and analyze profiles with commands like top, list, and web for CPU and memory data. 3. For non-HTTP apps, use runtime/pprof to write CPU and heap profiles to files and analyze them offline. 4. Interpret key metrics such as flat/cum CPU values, inuse_space in heap, and block/mutex contention to identify bottlenecks. 5. Visualize profiles using go tool pprof -web after installing graphviz, and generate SVGs for sharing. Profiling Go applications is built-in, efficient, and essential for performance optimization when done under realistic conditions with secure endpoint access.
Profiling Go applications is essential for identifying performance bottlenecks like CPU hogs, memory leaks, or excessive garbage collection. Go provides built-in tools through the pprof
package that make profiling straightforward. Here's how to do it effectively.

1. Use net/http/pprof
for Web Applications
If your Go application is a web server, the easiest way to enable profiling is by importing net/http/pprof
. This automatically adds several debugging endpoints to your HTTP server.
import _ "net/http/pprof" import "net/http" func main() { go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() // your app logic }
Once enabled, visit http://localhost:6060/debug/pprof/
in your browser to see available profiles:

/debug/pprof/profile
– CPU profile (30-second default)/debug/pprof/heap
– Heap memory allocation/debug/pprof/goroutine
– Goroutine stack traces/debug/pprof/block
– Goroutine blocking profile/debug/pprof/mutex
– Mutex contention
You can also fetch these profiles via curl
or go tool pprof
.
2. Collect and Analyze Profiles with go tool pprof
After enabling pprof
, collect a CPU profile:

go tool pprof http://localhost:6060/debug/pprof/profile
This downloads a 30-second CPU profile and opens an interactive session.
For memory:
go tool pprof http://localhost:6060/debug/pprof/heap
Common pprof
commands in the interactive shell:
top
– Show top functions by resource usagelist <function>
– Disassemble a specific functionweb
– Generate a visual call graph (requiresgraphviz
)trace
– Output trace of matching samplestext
– Print flat text report
You can also skip the shell and generate output directly:
go tool pprof -top http://localhost:6060/debug/pprof/heap
3. Profile Non-HTTP Applications
For CLI or background apps without HTTP servers, use the runtime/pprof
package directly.
CPU Profiling
f, _ := os.Create("cpu.prof") pprof.StartCPUProfile(f) defer pprof.StopCPUProfile() // run the code you want to profile
Memory Profiling
// capture heap profile f, _ := os.Create("heap.prof") defer f.Close() // do some work... pprof.WriteHeapProfile(f)
Then analyze with:
go tool pprof cpu.prof go tool pprof heap.prof
4. Interpret Key Metrics
- CPU Profile: Look for functions with high "flat" or "cum" values. These are consuming the most CPU time.
- Heap Profile: Check
inuse_space
for currently allocated memory. High values may indicate memory leaks. - Goroutine Profile: Useful for spotting goroutine leaks or deadlocks.
- Block/Mutex Profiles: Reveal synchronization bottlenecks.
Tip: Use
--nodefraction=0.05
inpprof
to hide small nodes and focus on significant contributors.
Bonus: Use pprof
with Visualization
Install graphviz
(brew install graphviz
or sudo apt-get install graphviz
), then:
go tool pprof -web cpu.prof
This generates and opens a visual flame graph-style call tree.
You can also generate SVGs:
go tool pprof -web -output=profile.svg cpu.prof
Profiling Go apps doesn’t require external tools—just enable pprof
, collect data under realistic load, and analyze. The key is to profile in an environment that mirrors production as closely as possible.
Basically, it’s built-in, lightweight, and powerful—just don’t forget to disable debug endpoints in production unless you lock them down.
The above is the detailed content of How to profile Go applications for performance?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The answer is: Go applications do not have a mandatory project layout, but the community generally adopts a standard structure to improve maintainability and scalability. 1.cmd/ stores the program entrance, each subdirectory corresponds to an executable file, such as cmd/myapp/main.go; 2.internal/ stores private code, cannot be imported by external modules, and is used to encapsulate business logic and services; 3.pkg/ stores publicly reusable libraries for importing other projects; 4.api/ optionally stores OpenAPI, Protobuf and other API definition files; 5.config/, scripts/, and web/ store configuration files, scripts and web resources respectively; 6. The root directory contains go.mod and go.sum

Using bufio.Scanner is the most common and efficient method in Go to read files line by line, and is suitable for handling scenarios such as large files, log parsing or configuration files. 1. Open the file using os.Open and make sure to close the file via deferfile.Close(). 2. Create a scanner instance through bufio.NewScanner. 3. Call scanner.Scan() in the for loop to read line by line until false is returned to indicate that the end of the file is reached or an error occurs. 4. Use scanner.Text() to get the current line content (excluding newline characters). 5. Check scanner.Err() after the loop is over to catch possible read errors. This method has memory effect

Routing in Go applications depends on project complexity. 1. The standard library net/httpServeMux is suitable for simple applications, without external dependencies and is lightweight, but does not support URL parameters and advanced matching; 2. Third-party routers such as Chi provide middleware, path parameters and nested routing, which is suitable for modular design; 3. Gin has excellent performance, built-in JSON processing and rich functions, which is suitable for APIs and microservices. It should be selected based on whether flexibility, performance or functional integration is required. Small projects use standard libraries, medium and large projects recommend Chi or Gin, and finally achieve smooth expansion from simple to complex.

BuildconstraintsinGoarecommentslike//go:buildthatcontrolfileinclusionduringcompilationbasedonconditionssuchasOS,architecture,orcustomtags.2.TheyareplacedbeforethepackagedeclarationwithablanklineinbetweenandsupportBooleanoperatorslike&&,||,and

Go's flag package can easily parse command line parameters. 1. Use flag.Type() to define type flags such as strings, integers, and booleans; 2. You can parse flags to variables through flag.TypeVar() to avoid pointer operations; 3. After calling flag.Parse(), use flag.Args() to obtain subsequent positional parameters; 4. Implementing the flag.Value interface can support custom types to meet most simple CLI requirements. Complex scenarios can be replaced by spf13/cobra library.

The if-else statement in Go does not require brackets but must use curly braces. It supports initializing variables in if to limit scope. The conditions can be judged through the elseif chain, which is often used for error checking. The combination of variable declaration and conditions can improve the simplicity and security of the code.

In Go, constants are declared using the const keyword, and the value cannot be changed, and can be of no type or type; 1. A single constant declaration such as constPi=3.14159; 2. Multiple constant declarations in the block are such as const(Pi=3.14159; Language="Go"; IsCool=true); 3. Explicit type constants such as constSecondsInMinuteint=60; 4. Use iota to generate enumeration values, such as const(Sunday=iota;Monday;Tuesday) will assign values 0, 1, and 2 in sequence, and iota can be used for expressions such as bit operations; constants must determine the value at compile time,

Gohandlesconcurrencythroughgoroutinesandchannels,enablingsimple,safe,andscalableconcurrentprogramming.1.GoroutinesarelightweightthreadsmanagedbytheGoruntime,startedwiththegokeyword,andrequireminimalresourcesduetosmall,growablestacks.2.Channelsfacilit
