by huachimingo · 4y ago · 0 comments
/logical comparison/ int greater_abs(int num, int x){ return (num > x) || (num+x < 0); }
/squared approach/ int greater_abs2(int num, int x){ return num*num > x; }
See it by yourself, with (and without) optimizations: https://godbolt.org/
What would happen if x is a compile-time constant?
Godbolt uses whatever compilers, targets, and optimisations you ask it to.
It is, in fact, a very useful tool for comparing different compilers, architectures, and optimization settings.
In practice, just writing "abs(num) > x" gives quite good machine code, and it does so without introducing hard-to-see bugs.
In the 2nd, which I assume should be
{ return num*num > x * x; }
then it depends on the micro-arch, as it's one basic block so no branches and assuming a deep pipeline on x64, one multiplier (pipelined), probably this is faster for 'random-ish' num and x.How frequently am I calling `abs`?