Simple profiling for Go

profile

Go Reference

Simple profiling for Go.

  • Easy management of Go's built-in profiling and tracing
  • Based on the widely-used pkg/profile: mostly-compatible API
  • Supports generating multiple profiles at once
  • Configurable with idiomatic flags: -cpuprofile, -memprofile, ... just like go test
  • Configurable by environment variable: key-value interface like GODEBUG

Install

go get github.com/mmcloughlin/profile

Usage

Enabling profiling in your application is as simple as one line at the top of your main function.

import "github.com/mmcloughlin/profile"

func main() {
	defer profile.Start().Stop()
	// ...
}

This will write a CPU profile to the current directory. Generate multiple profiles by passing options to the Start function.

defer profile.Start(profile.CPUProfile, profile.MemProfile).Stop()

Profiles can also be configured by the user via flags or environment variable, as demonstrated in the examples below.

Flags

The following example shows how to configure profile via flags with multiple available profile types.

func main() {
	log.SetPrefix("example: ")
	log.SetFlags(0)

	// Setup profiler.
	p := profile.New(
		profile.CPUProfile,
		profile.MemProfile,
		profile.TraceProfile,
	)

	// Configure flags.
	n := flag.Int("n", 1000000, "sum the integers 1 to `n`")
	p.SetFlags(flag.CommandLine)
	flag.Parse()

	// Start profiler.
	defer p.Start().Stop()

	// Sum 1 to n.
	sum := 0
	for i := 1; i <= *n; i++ {
		sum += i
	}
	log.Printf("sum: %d", sum)
}

See the registered flags:

Usage of example:
  -cpuprofile file
    	write a cpu profile to file
  -memprofile file
    	write an allocation profile to file
  -memprofilerate rate
    	set memory allocation profiling rate (see runtime.MemProfileRate)
  -n n
    	sum the integers 1 to n (default 1000000)
  -trace file
    	write an execution trace to file

Profile the application with the following flags:

example -n 1000000000 -cpuprofile cpu.out -memprofile mem.out

We'll see additional logging in the output, as well as the profiles cpu.out and mem.out written on exit.

example: cpu profile: started
example: mem profile: started
example: sum: 500000000500000000
example: cpu profile: stopped
example: mem profile: stopped

Environment

For a user-facing tool you may not want to expose profiling options via flags. The profile package also offers configuration by environment variable, similar to the GODEBUG option offered by the Go runtime.

	// Setup profiler.
	defer profile.Start(
		profile.AllProfiles,
		profile.ConfigEnvVar("PROFILE"),
	).Stop()

Now you can enable profiling with an environment variable, as follows:

PROFILE=cpuprofile=cpu.out,memprofile=mem.out example -n 1000000000

The output will be just the same as for the previous flags example. Set the environment variable to help to get help on available options:

PROFILE=help example

In this case you'll see:

blockprofile=file
	write a goroutine blocking profile to file
blockprofilerate=rate
	set blocking profile rate (see runtime.SetBlockProfileRate)
cpuprofile=file
	write a cpu profile to file
goroutineprofile=file
	write a running goroutine profile to file
memprofile=file
	write an allocation profile to file
memprofilerate=rate
	set memory allocation profiling rate (see runtime.MemProfileRate)
mutexprofile=string
	write a mutex contention profile to the named file after execution
mutexprofilefraction=int
	if >= 0, calls runtime.SetMutexProfileFraction()
threadcreateprofile=file
	write a thread creation profile to file
trace=file
	write an execution trace to file

Thanks

Thank you to Dave Cheney and contributors for the excellent pkg/profile package, which provided the inspiration and basis for this work.

License

profile is available under the BSD 3-Clause License. The license retains the copyright notice from pkg/profile.

Similar Resources

Lightweight, Simple, Quick, Thread-Safe Golang Stack Implementation

stack Lightweight, Simple, Quick, Thread-Safe Golang Stack Implementation Purpose Provide a fast, thread safe, and generic Golang Stack API with minim

May 3, 2022

simple i18n support that relies on standard go libraries

The i18n package mainly includes a set of methods for managing the data. Start by creating a en.json file.

Jun 29, 2021

A simple thread-safe, fixed size LRU written in Go. Based on dominictarr's Hashlru Algorithm. 🔃

go-hashlru A simple thread-safe, fixed size LRU written in Go. Based on dominictarr's Hashlru Algorithm. 🔃 Uses map[interface{}]interface{} to allow

Dec 5, 2022

Simple expression evaluation engine for Go

🌶️ chili Currently in development, Unstable (API may change in future) Simple expression evaluation engine. Expression is one liner that evalutes int

Nov 8, 2022

A simple tool to auto remove unused imports in rust

rust_strip A simple tool to remove unused imports in RUST. Call Cargo build/test Process the warning logs of unused imports Then replace the involved

Oct 15, 2022

A simple business indicator tool that uses a sliding window to detect whether the indicator exceeds the threshold

melon A simple business indicator tool that uses a sliding window to detect whether the indicator exceeds the threshold Usage //create the metric //th

Jul 11, 2021

Simple HTML Modification in Go

Simple HTML Modification in Go Do you grin at the sight of html.Node ? Me too. Modifying HTML in Go should be simple. 🧘🏻 Human friendly: query langu

Sep 29, 2021

simple GitHub action to parse Markdown Links into a .yaml file for Hugo

Obsidian Link Scrapper Used by Quartz This repository comes to you in two parts. GitHub Action (scrapes links into a .yml file) Hugo Partial (turns .y

Dec 30, 2022

A simple API for computing diffs of your documents over the time built on a scalable technology stack.

Diffme API WIP - this is an API to compute diffs between documents. It serves as a way to easily create audit logs for documents in your system, think

Sep 8, 2021
Related tags
perfessor - Continuous Profiling Sidecar

perfessor - Continuous Profiling Sidecar About Perfessor is a continuous profiling agent that can profile running programs using perf It then converts

Sep 28, 2022
Continuous profiling for analysis of CPU, memory usage over time, and down to the line number. Saving infrastructure cost, improving performance, and increasing reliability.
Continuous profiling for analysis of CPU, memory usage over time, and down to the line number. Saving infrastructure cost, improving performance, and increasing reliability.

Continuous profiling for analysis of CPU, memory usage over time, and down to the line number. Saving infrastructure cost, improving performance, and increasing reliability.

Jan 2, 2023
Go-generics-simple-doubly-linked-list - A simple doubly linked list implemented using generics (Golang)

Welcome to Go-Generics-Simple-Doubly-Linked-List! Hi, This repository contains a

Jun 30, 2022
Simple in Pure Go in Browser Interactive Interpreter
Simple in Pure Go in Browser Interactive Interpreter

GoBook This project is a PoC Don't take it seriously The main point of this project is the use of the library: github.com/brendonmatos/golive Maybe th

Feb 22, 2022
Simple project to demonstrate the loading of eBPF programs via florianl/go-tc.

tc-skeleton Simple project to demonstrate the loading of eBPF programs via florianl/go-tc.

Dec 23, 2022
EGo lets you build, debug und run Go apps on Intel SGX - as simple as conventional Go programming!

EGo lets you build, debug und run Go apps on Intel SGX - as simple as conventional Go programming!

Dec 28, 2022
A super simple Lodash like utility library with essential functions that empowers the development in Go
A super simple Lodash like utility library with essential functions that empowers the development in Go

A simple Utility library for Go Go does not provide many essential built in functions when it comes to the data structure such as slice and map. This

Jan 4, 2023
egg - the simple error aggregator

egg - the simple error aggregator egg ingests errors and aggregates them egg has 1st class support for sentry SDKs so you dont have to change any code

May 1, 2022
Procswap is a simple application that allows you to prioritize processes on a Windows machine.
Procswap is a simple application that allows you to prioritize processes on a Windows machine.

Procswap is a simple application that allows you to prioritize processes on a Windows machine.

Mar 8, 2022
Simple unpacking script for Ezuri ELF Crypter
Simple unpacking script for Ezuri ELF Crypter

ezuri_unpack A simple unpacking script for the Ezuri ELF Crypter. Based on the analysis done by Ofer Caspi and Fernando Martinez of AT&T Alien Labs

Dec 15, 2022