summaryrefslogtreecommitdiff
path: root/Benchmarking code in Golang.md
blob: 22d180d5b401c55cf4a02972b8ee4c1e8645d203 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
---
tags:
  - golang
  - howto
---
Simple timing can be done using the time package.
```
import time
import fmt

func main() {
	start := time.Now()
	elapsed = time.Since(start).Seconds()
	fmt.Printf("%.2fs", elapsed)
}
```

Writing benchmarks. They look similar to tests:
```
import testing

func BenchmarkSome(b *testing.B) {
	for i := 0; i < b.N; i++ {
		Some()
	}
}
```
b.N is supplied by test driver and is dynamically changed depending on runtime.

`go test -bench=<regex>`

This just benchmarks a function being called many times, comparative benchmarks can be written using a regular function being called from Benchmarks, something like so :
```
import testing

func doBench(b *testing.B, size int) { ... vary inputs size }
func Bench1(b *testing.B)
func Bench10(b *testing.B)
func Bench100(b * testing.B)
```