Created
April 11, 2013 14:05
-
-
Save songgao/5363647 to your computer and use it in GitHub Desktop.
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
/* | |
Benchmarking against different approaches to calculate Max() of int. | |
* Patented (WTF?!) Abs used. http://stackoverflow.com/a/9962527/218439 | |
Results; | |
slice size: 1 | |
min_with_branching: 200000000 9.28 ns/op | |
min_without_branching: 100000000 13.2 ns/op | |
slice size: 128 | |
min_with_branching: 100000000 13.4 ns/op | |
min_without_branching: 100000000 14.6 ns/op | |
slice size: 1024 | |
min_with_branching: 100000000 15.7 ns/op | |
min_without_branching: 100000000 14.0 ns/op | |
slice size: 65536 | |
min_with_branching: 100000000 16.4 ns/op | |
min_without_branching: 100000000 14.1 ns/op | |
*/ | |
package main | |
import ( | |
"fmt" | |
"math/rand" | |
"testing" | |
) | |
func min_with_branching(a int, b int) int { | |
if a < b { | |
return a | |
} | |
return b | |
} | |
func min_without_branching(x int, y int) int { | |
// abs := (d ^ (d >> 31)) - (d >> 31) | |
// min := (a+b-abs(a-b))/2 | |
d := x - y | |
return (x + y - ((d ^ (d >> 31)) - (d >> 31))) / 2 | |
} | |
func benchmark(S_nums int) { | |
fmt.Printf("slice size: %d\n", S_nums) | |
nums := make([]int, S_nums) | |
for i := 0; i < S_nums; i++ { | |
nums[i] = rand.Int() | |
} | |
fmt.Printf("min_with_branching: %s\n", testing.Benchmark(func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = min_with_branching(nums[i%S_nums], nums[(i+1)%S_nums]) | |
} | |
}).String()) | |
fmt.Printf("min_without_branching: %s\n", testing.Benchmark(func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
_ = min_without_branching(nums[i%S_nums], nums[(i+1)%S_nums]) | |
} | |
}).String()) | |
fmt.Println("") | |
} | |
func main() { | |
benchmark(1) | |
benchmark(128) | |
benchmark(1024) | |
benchmark(65536) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment