Skip to main content



Benchmarks are provided by Go testing library and are written in a similar way to how you write Go tests:

Benchmarks are placed in _test.go files.

They start with Benchmark instead of Test.

The benchmarked code is placed inside this loop:

    for i := 0; i < b.N; i++ {
// your code to benchmark


Bellow I try to benchmark to functions Hello() and Hi:

package andrei

import (

func Hello() {
time.Sleep(1 * time.Second)

func Hi() {
time.Sleep(500 * time.Millisecond)

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

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

Running the benchmarks

Running benchmarks in current directory:

go test -run none -bench .

Running benchmarks with checking memory allocations:

go test -run none -bench . -benchmem

Interpreting results

My output on above benchmark:

goos: linux
goarch: amd64
pkg: andrei/andrei
cpu: 11th Gen Intel(R) Core(TM) i7-1165G7 @ 2.80GHz
BenchmarkHello-8 1 1000071854 ns/op 88 B/op 2 allocs/op
BenchmarkHi-8 2 500798674 ns/op 44 B/op 1 allocs/op
ok andrei/andrei 2.507s

An image describing how to read benchmark results, courtesy of Practical Go Lessons:

Example banner