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
- Host: GitHub
- URL: https://github.com/tomnomnom/branchdemo
- Owner: tomnomnom
- Created: 2015-06-20T11:25:14.000Z (almost 10 years ago)
- Default Branch: master
- Last Pushed: 2015-06-20T21:36:32.000Z (almost 10 years ago)
- Last Synced: 2025-01-24T09:08:20.978Z (3 months ago)
- Language: Go
- Size: 121 KB
- Stars: 2
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.mkd
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 := 0for _, 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.301sIntel(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.907sAMD 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