Skip to content

Instantly share code, notes, and snippets.

@kgaughan
Created August 4, 2019 13:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kgaughan/1fd890cc84f21d6b1a8c733af282cc55 to your computer and use it in GitHub Desktop.
Save kgaughan/1fd890cc84f21d6b1a8c733af282cc55 to your computer and use it in GitHub Desktop.
Iteration benchmark
package iteration
func fiboChan(n int) <-chan int {
c := make(chan int)
go func() {
a := 0
b := 1
for i := 0; i < n; i++ {
a, b = b, a+b
c <- a
}
close(c)
}()
return c
}
package iteration
import "testing"
func BenchmarkFiboChan(b *testing.B) {
for j := 0; j < b.N/10000; j++ {
c := fiboChan(10000)
for i := range c {
_ = i
}
}
}
package iteration
type FiboIter struct {
a, b int
}
func NewFiboIter() FiboIter {
return FiboIter{0, 1}
}
func (c *FiboIter) Next() int {
c.a, c.b = c.b, c.a+c.b
return c.a
}
package iteration
import "testing"
func BenchmarkFiboIter(b *testing.B) {
for j := 0; j < b.N/10000; j++ {
c := NewFiboIter()
for i := 0; i < 10000; i++ {
_ = c.Next()
}
}
}
u0_a99@localhost ~/p/g/src> go test -bench . -cpu 1 -count 10 iteration
goos: android
goarch: arm64
pkg: iteration
BenchmarkFiboChan 5000000 266 ns/op
BenchmarkFiboChan 5000000 347 ns/op
BenchmarkFiboChan 5000000 271 ns/op
BenchmarkFiboChan 5000000 274 ns/op
BenchmarkFiboChan 5000000 273 ns/op
BenchmarkFiboChan 5000000 294 ns/op
BenchmarkFiboChan 5000000 288 ns/op
BenchmarkFiboChan 5000000 275 ns/op
BenchmarkFiboChan 5000000 286 ns/op
BenchmarkFiboChan 5000000 285 ns/op
BenchmarkFiboIter 2000000000 1.16 ns/op
BenchmarkFiboIter 2000000000 1.17 ns/op
BenchmarkFiboIter 2000000000 1.11 ns/op
BenchmarkFiboIter 2000000000 1.13 ns/op
BenchmarkFiboIter 2000000000 1.18 ns/op
BenchmarkFiboIter 2000000000 1.18 ns/op
BenchmarkFiboIter 2000000000 1.15 ns/op
BenchmarkFiboIter 2000000000 1.18 ns/op
BenchmarkFiboIter 2000000000 1.18 ns/op
BenchmarkFiboIter 2000000000 1.15 ns/op
BenchmarkFiboSlice 500000000 3.38 ns/op
BenchmarkFiboSlice 500000000 3.38 ns/op
BenchmarkFiboSlice 500000000 3.35 ns/op
BenchmarkFiboSlice 500000000 3.33 ns/op
BenchmarkFiboSlice 500000000 3.28 ns/op
BenchmarkFiboSlice 500000000 3.44 ns/op
BenchmarkFiboSlice 500000000 3.37 ns/op
BenchmarkFiboSlice 500000000 3.33 ns/op
BenchmarkFiboSlice 500000000 3.40 ns/op
BenchmarkFiboSlice 500000000 3.42 ns/op
PASS
ok iteration 62.201s
u0_a99@localhost ~/p/g/src>
package iteration
func fiboSlice(n int) []int {
result := make([]int, n)
a := 0
b := 1
for i := 0; i < n; i++ {
a, b = b, a+b
result[i] = a
}
return result
}
package iteration
import "testing"
func BenchmarkFiboSlice(b *testing.B) {
for j := 0; j < b.N/10000; j++ {
c := fiboSlice(10000)
for _, i := range c {
_ = i
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment