Last active
April 29, 2020 11:39
-
-
Save dimmaq/ad83afd5fcc3263a87d8c9fc47cffccd to your computer and use it in GitHub Desktop.
fizzbuzz golang benchmark
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "testing" | |
func f0(n int) (k int, k3 int, k5 int, k15 int) { | |
for i := 1; i <= n; i++ { | |
if i%3 == 0 { | |
//print("Foo") | |
k3++ | |
} | |
if i%5 == 0 { | |
//print("Bar") | |
k5++ | |
} | |
if i%3 == 0 && i%5 == 0 { | |
k15++ | |
} | |
if i%3 != 0 && i%5 != 0 { | |
//print(i) | |
k++ | |
} | |
//println() | |
} | |
return | |
} | |
func f1(n int) (k int, k3 int, k5 int, k15 int) { | |
for i := 1; i <= n; i++ { | |
b3 := i%3 == 0 | |
b5 := i%5 == 0 | |
if b3 || b5 { | |
if b3 && b5 { | |
k15++ | |
k5++ | |
k3++ | |
} else if b3 { | |
k3++ | |
} else { | |
k5++ | |
} | |
} else { | |
k++ | |
} | |
} | |
return | |
} | |
func f2(n int) (k int, k3 int, k5 int, k15 int) { | |
for i, i3, i5 := 1, 1, 1; i <= n; i++ { | |
if i3 == 3 { | |
k3++ | |
i3 = 0 | |
} | |
if i5 == 5 { | |
k5++ | |
i5 = 0 | |
} | |
if i3 == 0 && i5 == 0 { | |
k15++ | |
} else if i3 != 0 && i5 != 0 { | |
k++ | |
} | |
i3++ | |
i5++ | |
} | |
return | |
} | |
func f3(n int) (k int, k3 int, k5 int, k15 int) { | |
for i := 1; i <= n; i++ { | |
if i%3 == 0 { | |
if i%5 == 0 { | |
k3++ | |
k5++ | |
k15++ | |
continue | |
} | |
k3++ | |
continue | |
} | |
if i%5 == 0 { | |
k5++ | |
continue | |
} | |
k++ | |
} | |
return | |
} | |
func TestF(t *testing.T) { | |
for j := 0; j < 42000; j++ { | |
i, i3, i5, i15 := f0(j) | |
if (i3 + i5 - i15 + i) != j { | |
t.Errorf("f0(%d) == (%d, %d, %d, %d)", j, i, i3, i5, i15) | |
return | |
} | |
k, k3, k5, k15 := f1(j) | |
if k != i || k3 != i3 || k5 != i5 || k15 != i15 { | |
t.Errorf("f1(%d) == (%d, %d, %d, %d), need (%d, %d, %d, %d)", j, k, k3, k5, k15, i, i3, i5, i15) | |
return | |
} | |
k, k3, k5, k15 = f2(j) | |
if k != i || k3 != i3 || k5 != i5 || k15 != i15 { | |
t.Errorf("f2(%d) == (%d, %d, %d, %d), need (%d, %d, %d, %d)", j, k, k3, k5, k15, i, i3, i5, i15) | |
return | |
} | |
k, k3, k5, k15 = f3(j) | |
if k != i || k3 != i3 || k5 != i5 || k15 != i15 { | |
t.Errorf("f3(%d) == (%d, %d, %d, %d), need (%d, %d, %d, %d)", j, k, k3, k5, k15, i, i3, i5, i15) | |
return | |
} | |
} | |
} | |
func BenchmarkF0(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
f0(1000000) | |
} | |
} | |
func BenchmarkF1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
f1(1000000) | |
} | |
} | |
func BenchmarkF2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
f2(1000000) | |
} | |
} | |
func BenchmarkF3(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
f3(1000000) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment