3 ms·
> i * 28 == i<<4 + i<<3 + i<<2 gcc will do these kind of optimizations, when they make sense. But for 28, most processors will actually be faster doing the mul
by joosters 11y ago
> i * 28 == i<<4 + i<<3 + i<<2
gcc will do these kind of optimizations, when they make sense. But for 28, most processors will actually be faster doing the multiply.
Multiply instructions only take a few clock cycles. A sequence of adds and shifts can also be slower because they are a sequence of dependent instructions - you need the result of the first one to calculate the next. (You can do some of the adds in parallel, but you still need to total them up)
Here's some old data for an ancient ARM9 processor - http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0091a/BEIEDGJJ.html http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.... - it takes 2-5 cycles for a MUL (3 for a MUL of 28), compared with 1 for an ADD, 2 for an ADD with shift.
So your 'optimization' would take 6 cycles on an ARM 9, while the MUL takes 3.
It's really easy to double check this. Compile this dumb code with 'gcc -s -O3 test.c'
#include <stdio.h>
int main(int argc, char *argv[])
{
int i = argc;
printf("%d\n", i*28);
return 0;
}
Try changing the 28 to different values and run a diff against each version (e.g. try 8, 9 and 10). On x86, gcc will use a variety of techniques based upon the multiplier.
- lorenzhs 11y agoit's even easier to play around with these things using https://gcc.godbolt.org https://gcc.godbolt.org