Compiler optimizations

Walter Bright newshound at digitalmars.com
Tue May 2 02:00:17 PDT 2006


Craig Black wrote:
> These two functions show the difference that I'm talking about.  When
> benchmarking, pass in the same values for the divisor (pick a value between
> 2 and 30), and pass in a large enough value for total so that it will take
> some time for the CPU to finish.  Suprisingly, the second one is faster.

Multiplication is a much simpler operation than division, which is why 
it's faster. Secondly, the reason compilers don't do the optimization 
below is that it gives different results (different rounding).

If you're really interested in optimization, I suggest using a 
disassembler on the object files, it will answer a lot of questions.


> int divTest1(int divisor, int total)
> {
>   int sum = 0;
>   for(int i = 0; i < total; i++)
>   {
>     int quotient = i / divisor;
>     sum += quotient;
>   }
> }
> 
> int divTest2(int divisor, int total)
> {
>   int sum = 0;
>   double idiv = 1.0 / divisor;
>   for(int i = 0; i < total; i++)
>   {
>     int quotient = i * idiv;
>     sum += quotient;
>   }
> }




More information about the Digitalmars-d mailing list