Page 1 of 1

Optimizing Code With C

PostPosted: Tue Apr 15, 2008 11:47 pm
by Wyrmkill
Code: Select all
/*
    Optimize code by shifting
*/

unsigned __int16
    __cdecl printf(const char*, ...),
    __cdecl getch(void);

void main(void) {

Instead of dividing 'a' with 16 (2^4) we shift
its bits four positions to the right.

By using this we can skip the consuming;
mov ecx, 16 <-- 1c
mov eax,dword ptr [a] <-- 1c
cdq <-- 3c
idiv ecx <-- 46c
mov dword ptr [a], eax <-- 1c

And replace it with;
sar dword ptr [a], 4 <-- 3c

Dividing 'a' with 16 will need 52c (cycles),
and shifting bits will only need 3c (cycles)!

That is an impressive optimization

The following code will show you how the
optimizing is done using C code:
Code: Select all
    unsigned __int16 a = 0x64;  // a = 100
    a >>= 4;                    // a = a/16
    printf("%d\x0A",a);         // send result to stout
    getch();                    // wait for kbhit

}

Re: Optimizing Code With C

PostPosted: Wed Apr 16, 2008 10:35 am
by evinyatar
As far as i know compilers replace all multiplication and division by powers of two with shifts, so there is no reason to do it manually.

Re: Optimizing Code With C

PostPosted: Wed Apr 16, 2008 11:52 am
by BhaaL
evinyatar wrote:As far as i know compilers replace all multiplication and division by powers of two with shifts, so there is no reason to do it manually.

Not all compilers do that, especially not on their own. GCC afaik only does that on a certain optimization level; the Visual Studio C++ compiler fails completely (at least last time looked, it used a plain idiv).

Still, neat thing.

Re: Optimizing Code With C

PostPosted: Wed Apr 16, 2008 3:19 pm
by Sonic7145
Pretty cool, nice work.

Re: Optimizing Code With C

PostPosted: Wed Apr 23, 2008 8:48 am
by -Pein-God-
yea...this is cool ;) ;)

Re: Optimizing Code With C

PostPosted: Thu Jun 05, 2008 4:24 pm
by djpitagora
BhaaL wrote:
evinyatar wrote:As far as i know compilers replace all multiplication and division by powers of two with shifts, so there is no reason to do it manually.

Not all compilers do that, especially not on their own. GCC afaik only does that on a certain optimization level; the Visual Studio C++ compiler fails completely (at least last time looked, it used a plain idiv).

Still, neat thing.


I don't know what visual studio compiler you are using or what options but normaly it does optimize this. Try changing the goal from size to speed. I've seen some pretty incredible optimizations done by the compiler and not only for multiplications or divisions by a power of two: multiplication by 3 can be done with one shift and an add for instance...and so on...