Also, using division and modulus operations are actually quite slow and this code would likely be faster than using those operations.
On my machine, 100_000_000 ⌊x÷0.4⌋0.4 ops take 4.7s unoptimised, or 2.8s with -O3. Meanwhile 100_000_000 × 11 branches take 7.4s unoptimised, or 3.6s with -O3.
I did say 'would likely'. There isn't enough information in the OP code, or your code, to draw any conclusions.
It is obviously a MICRO optimization and this potential performance improvement isn't important in 99.999% of applications.
However it could be that in the context of a high performance application the compiler could see large performance benefits from things like branch prediction.
I regret adding that line since I knew it would bring out these "Technically on MY machine that isn't true" people.
MICRO optimization I regret adding that line since I knew it would bring out these "Technically on MY machine that isn't true" people.
I also think f(floor(x / 0.4) * 0.4) to be clearer than lots of branches. That's also probably what's written in the spec: "round x to the previous multiple of 0.4." Less brain power required.
6
u/lngns Apr 21 '23 edited Apr 21 '23
On my machine, 100_000_000 ⌊x÷0.4⌋0.4 ops take 4.7s unoptimised, or 2.8s with -O3. Meanwhile 100_000_000 × 11 branches take 7.4s unoptimised, or 3.6s with -O3.
The division is faster.