Measure Execution Time

October 4, 2019
golang | pattern

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"
fmt.Println(duration)

// Nanoseconds as int64
fmt.Println(duration.Nanoseconds())

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))
}

Benchmarks

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++ {
        fmt.Sprintf("hello")
    }
}

When you run it, it will output:

BenchmarkHello    10000000    282 ns/op