Compiler optimizations

Ben Phillips Ben_member at pathlink.com
Sun Apr 30 11:52:36 PDT 2006


In article <e32q1p$22dv$1 at digitaldaemon.com>, Craig Black says...
>
>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.
>
>-Craig
>
>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;
>  }
>}
>

The second one is faster because you cheat. You aren't testing integer division
but rather floating point multiplication. The first one has to divide every time
through the loop, the second one only has to multiply. Multiplication is much
faster than division (even floating point multiplication vs integer division),
so your results are not surprising and are not really useful.





More information about the Digitalmars-d mailing list