Created
January 27, 2024 19:16
-
-
Save berkes/de52e9bdfbb8c4c3164de352b46dadd0 to your computer and use it in GitHub Desktop.
"Benchmarking" some micro optimizations: strange behaviour.
This file contains 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
use std::time::Instant; | |
fn main() { | |
let iterations = 1_000_000; | |
let mut odd_count = 0; | |
// Using modulus | |
let start_modulus = Instant::now(); | |
for i in 0..iterations { | |
if i % 2 != 0 { | |
odd_count += 1; | |
} | |
} | |
let duration_modulus = start_modulus.elapsed(); | |
println!("Modulus: {:?} to count {} odd numbers", duration_modulus, odd_count); | |
// Reset odd_count | |
odd_count = 0; | |
// Using bitwise AND | |
let start_bitwise = Instant::now(); | |
for i in 0..iterations { | |
if i & 1 == 1 { | |
odd_count += 1; | |
} | |
} | |
let duration_bitwise = start_bitwise.elapsed(); | |
println!("Bitwise AND: {:?} to count {} odd numbers", duration_bitwise, odd_count); | |
} |
Modulus: 39.295µs to count 500000 odd numbers
Bitwise AND: 207.765µs to count 500000 odd numbers
Wow. that's even worse performing for bitwise and. Something weird is going on!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try it again with optimization enabled.