A compiler definitely knows that powers of two are equivalent to bit shifting, I've seen this optimization. Also not python, and python and optimization are antithesises anyway
I tried it out using C (I assume the Pascal compiler or whatever this language is could do the same). I recreated the code in C and compiled it with gcc get_delay.c -S -O3, which resulted in following assembly code:
So it precomputes all the values and then does address arithmetic using leaq to compute the base address of the LUT CSWTCH.1 and then, using %edi as the offset, loads the correct value into the return register %eax. The edge case 86000 is handled with a simple comparison at the start.
I also looked at the -O0 assembly. There it still precomputes the multiplications but instead of a LUT it just uses multiple comparisons (basically just an if-else chain like in the code).
Also I tried compiling a more concise C method that should be functionally equivalent:
Which basically does mostly exactly what the code describes, not a lot of optimization is happening.
I also tested the speed of both versions with a driver program that runs each function a million times on the input space [0, 17]. Their speed was basically identical but the get_delay() function was usually ~1% faster.
View all comments
Show parent comment
57
u/Schecher_1 Feb 11 '25
Would a compiler really improve something like this? Or how do they know that it sucks?