Measure a piece of code

// Record the start time
start := time.Now()

// Code to measure
duration := time.Since(start)

// Formatted string, such as "2h3m0.5s" or "4.503μs"

// Nanoseconds as int64

Measure a function call

You can track the execution time of a complete function call with this one-liner, which logs the result to the standard error stream.

func foo() {
    defer duration(track("foo"))
    // Code to measure

func track(msg string) (string, time.Time) {
    return msg, time.Now()

func duration(msg string, start time.Time) {
    log.Printf("%v: %v\n", msg, time.Since(start))


The testing package has support for benchmarking that can be used to examine the performance of your code.

func BenchmarkHello(b *testing.B) {
    for i := 0; i < b.N; i++ {

When you run it, it will output:

BenchmarkHello    10000000    282 ns/op

Related Posts

  • Assert vs require in testify
  • Handling Unix timestamps in JSON
  • Parsing a key pair from a PEM file in Go
  • Pointer vs value receivers
  • The beauty of io.Reader in Go