Measure Go Code Segment Performance and Detect Bottlenecks

StackImpact automatically covers many aspects of application performance measurement. These include hot spots in CPU usage, memory allocations, I/O, channels and lock contention. It also provides a bottleneck view for HTTP handlers and calls as well as multiple runtime metrics.

It is sometimes necessary to measure application specific code performance and trace bottlenecks. For these cases, StackImpact agent provides very simple, but powerful API:

segment := agent.MeasureSegment("Segment1")
defer segment.Stop()
subsegment := agent.MeasureSubsegment("Segment1", "Subsegment1")
defer subsegment.Stop()

The following example demonstrates a basic usage.

package main

import (


var agent *stackimpact.Agent

func exampleHandler(w http.ResponseWriter, r *http.Request) {
	segment := agent.MeasureSegment("Example")
	defer segment.Stop()


	fmt.Fprintf(w, "Done")

func doSomeAPICall() {
	subsegment := agent.MeasureSubsegment("Example", "API call")
	defer subsegment.Stop()

	res, err := http.Get("")
	if err == nil {
		defer res.Body.Close()

func readSomeDir() {
	subsegment := agent.MeasureSubsegment("Example", "Directory read")
	defer subsegment.Stop()


func main() {
	// Initialize StackImpact agent
	agent = stackimpact.NewAgent()
		AgentKey: "agent key here",
		AppName: "Example App",

	// Start server
	http.HandleFunc("/example", exampleHandler)
	http.ListenAndServe(":9000", nil)

Note, that there is no need to pass a context to trace subsegments of a segment. This makes the usage simple even in complex applications.

After generating some load against our example application, here is what we will see in the Dashboard. If no subsegments are measured, the metric is only available in Health section and not in Bottlenecks section.


Now we know how long the measured segment normally takes and what impact subsegments have on it.

Follow us on Twitter @stackimpact for information on Golang performance profiling and monitoring.