Instantly share code, notes, and snippets.

Embed
What would you like to do?
A better loop benchmark
#![feature(test)]
#![feature(step_by)]
extern crate test;
fn for_loop() -> usize {
let mut counter = 1;
for i in (0..1_000_000) {
counter += test::black_box(i);
}
counter
}
fn for_step_loop() -> usize {
let mut counter = 1;
for i in (0..1_000_000).step_by(1) {
counter += test::black_box(i);
}
counter
}
fn while_loop() -> usize {
let mut i=0;
let mut counter = 1;
while i < 1_000_000
{
counter += test::black_box(i);
i += 1
}
counter
}
#[bench]
fn bench_for(bench:&mut test::Bencher) {
bench.iter(for_loop);
}
#[bench]
fn bench_for_step(bench:&mut test::Bencher) {
bench.iter(for_step_loop);
}
#[bench]
fn bench_while(bench:&mut test::Bencher) {
bench.iter(while_loop);
}
/*
$ rustc -C opt-level=3 loops.rs --test && ./loops --bench
running 3 tests
test bench_for ... bench: 1,126,115 ns/iter (+/- 1,494)
test bench_for_step ... bench: 1,538,970 ns/iter (+/- 56,400)
test bench_while ... bench: 1,150,486 ns/iter (+/- 12,384)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment