r/programminghelp • u/stupidityWorks • Nov 20 '21
Other What's the most efficient isEven function?
I'm mostly just curious, but what's the fastest one?
You have the obligatory x % 2 == 0, as well as x & 1 == 0.
Which one of those is faster, and is there an even faster way to determine whether a number is even?
I mostly use rust, but I'm also curious about whether this extends to other languages.
Thanks!
4
Upvotes
1
6
u/Th3Dome Nov 20 '21 edited Nov 20 '21
I know, when you are programming Rust, you usually come to a point where you ask yourself, how you get the most performance out of your code. But that's is not how it works in modern languages. The compiler itself tries to guess many different things already in compilation. Like if an "if" is actually needed or the const can be inferred at compile time and thus making it obsolete to even consider the if. In Higher optimization levels things even get weirder like if a function is worth being kept as a function or if it should be inlined. All those things contribute to a fast and efficient program. I have assembled two examples:
like you can see, these programs are in fact the same except the comp function. I already need to import a "randomness" to prevent the compiler from discarding my let and just inlining the let time.
Now the assembly from the comp function looks like:
where you can see, the compiler doesn't even execute the desired code since it knows a more efficient solution. In fact this is the same code for both files. You can assemble this yourself using:
rustc and.rs -C llvm-args=-x86-asm-syntax=intel --emit asm -C opt-level=0So you see. It really does not make a difference, if you use and and or a mod operation since the compiler has its own idea of your code anyway.
But when you want to be very specific, it come to a comparison of the
DIVandANDoperation. This really depends on the CPU you are using, the microarchitecture and even the macrocode version (i.e. software running on a CPU directly coded into it during manufacturing).You can generally say that a
DIVis considerably slower than anAND. But we are actually talking about clock cycles here. You just have to imagine how many clock cycles are in one second in a mid-grade cpu (like 2.9Ghz). Even milliseconds are too big to talk about the latency. So you won't even feel the difference.Edit: replace mod instruction with div since mod does not exist