Skip to content

Instantly share code, notes, and snippets.

@berkes
Created January 27, 2024 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save berkes/de52e9bdfbb8c4c3164de352b46dadd0 to your computer and use it in GitHub Desktop.
Save berkes/de52e9bdfbb8c4c3164de352b46dadd0 to your computer and use it in GitHub Desktop.
"Benchmarking" some micro optimizations: strange behaviour.
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);
}
@pictographer
Copy link

Try it again with optimization enabled.

# Compilation provided by Compiler Explorer at https://godbolt.org/

Standard error:
warning: function `main` is never used
 --> <source>:3:4
  |
3 | fn main() {
  |    ^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: 1 warning emitted


# Execution result with exit code 0
# Standard out:
Modulus: 39.295µs to count 500000 odd numbers
Bitwise AND: 207.765µs to count 500000 odd numbers

@berkes
Copy link
Author

berkes commented Feb 9, 2024

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