r/programminghelp • • 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

3 comments sorted by

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:

and.rs

use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    comp(since_the_epoch.as_micros());
}

fn comp(time: u128) {
    if time & 1 == 0 {
        println!("{}", time);
    }
}

mod.rs

use std::time::{SystemTime, UNIX_EPOCH};

fn main() {
    let start = SystemTime::now();
    let since_the_epoch = start
        .duration_since(UNIX_EPOCH)
        .expect("Time went backwards");
    comp(since_the_epoch.as_micros());
}

fn comp(time: u128) {
    if time % 2 == 0 {
        println!("{}", time);
    }
}

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:

_ZN3mod4comp17h1ade0b213446d7a3E:
	.cfi_startproc
	sub	rsp, 104
	.cfi_def_cfa_offset 112
	mov	qword ptr [rsp + 16], rdi
	mov	qword ptr [rsp + 24], rsi
	mov	al, byte ptr [rsp + 16]
	test	al, 1
	jne	.LBB20_2
	jmp	.LBB20_1

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=0

So 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 DIV and AND operation. 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 DIV is considerably slower than an AND. 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.

So, TL;DR It doesn't make a difference.

Edit: replace mod instruction with div since mod does not exist

1

u/Coulomb111 Nov 22 '21

I love this answer

1

u/iraqmtpizza Nov 22 '21

% is slower than & in Java if I recall