#development #golang #pattern

Measure a piece of code

 1// Record the start time
 2start := time.Now()
 3
 4// Code to measure
 5duration := time.Since(start)
 6
 7// Formatted string, such as "2h3m0.5s" or "4.503μs"
 8fmt.Println(duration)
 9
10// Nanoseconds as int64
11fmt.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.

 1func foo() {
 2    defer duration(track("foo"))
 3    // Code to measure
 4}
 5
 6func track(msg string) (string, time.Time) {
 7    return msg, time.Now()
 8}
 9
10func duration(msg string, start time.Time) {
11    log.Printf("%v: %v\n", msg, time.Since(start))
12}

Benchmarks

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

1func BenchmarkHello(b *testing.B) {
2    for i := 0; i < b.N; i++ {
3        fmt.Sprintf("hello")
4    }
5}

When you run it, it will output:

BenchmarkHello    10000000    282 ns/op