An open API service indexing awesome lists of open source software.

https://github.com/tomnomnom/branchdemo

CPU Branch Predictor Demo
https://github.com/tomnomnom/branchdemo

Last synced: about 2 months ago
JSON representation

CPU Branch Predictor Demo

Awesome Lists containing this project

README

        

# Branch Predictor Demo

Some example code to demonstrate the effects a CPU's [branch predictor](https://en.wikipedia.org/wiki/Branch_predictor) can
have on performance.

The example function counts the occurences of an integer in a slice of integers.

```go
func CountInt(search int, ints []int) int {
count := 0

for _, num := range ints {
if num == search {
count++
}
}

return count
}
```

When the provided integers are unsorted, the CPU's branch predictor is unable to reliably predict if the `num == search`
branch of the code will be followed on each iteration, incurring a penalty each time the prediction is wrong.
However, when the integers are sorted: every occurrence of the `num == search` branch being followed will happen consecutively,
allowing the branch predictor to be correct more often.

The included benchmarks count the occurences of the number 7 in a slice of 10,000 random integers between 0 and 100.

Note that the 'sorted' benchmark includes the time taken to sort the integers (once), and is therefore doing slightly more work.

## Example Benchmark Runs

Intel(R) Core(TM) i7-2670QM CPU @ 2.20GHz; go version go1.4.2 linux/amd64 (Laptop):

tom@megatron:~/src/github.com/tomnomnom/branchdemo (master)▶ go test -bench .
PASS
BenchmarkCountIntUnsorted 200000 8874 ns/op
BenchmarkCountIntSorted 200000 6778 ns/op
ok github.com/tomnomnom/branchdemo 3.301s

Intel(R) Xeon(R) CPU E5-2630L v2 @ 2.40GHz; go version go1.4.2 linux/amd64 (Digital Ocean, $5/mo instance):

tom@sh:~/src/github.com/tomnomnom/branchdemo (master)▶ go test -bench .
PASS
BenchmarkCountIntUnsorted 200000 10605 ns/op
BenchmarkCountIntSorted 200000 7926 ns/op
ok github.com/tomnomnom/branchdemo 3.907s

AMD Turion(tm) II Neo N54L Dual-Core Processor; go version go1.4.2 linux/amd64 (HP Proliant N54L):

tom@nabu:~/src/github.com/tomnomnom/branchdemo (master)▶ go test -bench .
PASS
BenchmarkCountIntUnsorted 100000 23593 ns/op
BenchmarkCountIntSorted 100000 22782 ns/op
ok github.com/tomnomnom/branchdemo 5.131s