Skip to content

Instantly share code, notes, and snippets.

@digitaldreamer
Last active February 25, 2020 20:44
Show Gist options
  • Save digitaldreamer/9738ed74a3b175a37f4f92bd16e5bcef to your computer and use it in GitHub Desktop.
Save digitaldreamer/9738ed74a3b175a37f4f92bd16e5bcef to your computer and use it in GitHub Desktop.
benchmarking looping arrays in go
/*
Summary
As expected, the time increase to loop an array is linear.
If we consider anything under 1ms as unnoticable then everything up to around 1 mil is realtively safe
depending on the work that you're doing.
The run times of 100 mil and larger have a lot of variance because of the low iteration counts so the overall
runtime is unreliable (i.e. too much of the run is taken up by allocating the array), but their runtimes
appear to be significant at those lengths.
Approx run times in human numbers
10 = 8 ns
1000 = .0006 ms
10,000 = .006 ms
100,000 = .05 ms
1 mil = .5 ms
10 mil = 5 ms
100 mil = 592 ms
1 bil = 14,000 ms
RESULTS
go test -bench=.
goos: darwin
goarch: amd64
pkg: golabs/looper
BenchmarkLoop/10-12 137666691 8.03 ns/op
BenchmarkLoop/1000-12 2123434 577 ns/op
BenchmarkLoop/10000-12 229411 6234 ns/op
BenchmarkLoop/100000-12 21679 56173 ns/op
BenchmarkLoop/1,000,000-12 1868 535689 ns/op
BenchmarkLoop/10,000,000-12 200 5367197 ns/op
BenchmarkLoop/100,000,000-12 2 592390966 ns/op
BenchmarkLoop/1,000,000,000-12 1 14077078769 ns/op
PASS
ok golabs/looper 26.782s
*/
////////////////////////////// looper.go
package looper
import "fmt"
type Things []string
// loop just a dumb function simply to loop through the array
func (t Things) loop() {
looped := len(t) * -1
for i := 0; i < len(t); i++ {
// just do some meaningless logic
// we're really doing some important work here
eq := false
looped++
eq = looped == i
if looped == i {
fmt.Println(eq)
}
}
return
}
////////////////////////////// looper_test.go
package looper
import (
"testing"
)
func BenchmarkLoop(b *testing.B) {
tests := []struct {
name string
length int
}{
{"10", 10},
{"1000", 1000},
{"10000", 10000},
{"100000", 100000},
{"1,000,000", 1000000},
{"10,000,000", 10000000},
{"100,000,000", 100000000},
{"1,000,000,000", 1000000000},
}
for _, test := range tests {
b.Run(test.name, func(b *testing.B) {
benched := make(Things, test.length)
for i := 0; i < b.N; i++ {
benched.loop()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment