Summary: for-loop end-condition optimization
--- Comment #0 from minas_mina1...@hotmail.co.uk 2012-04-06 01:14:27 PDT ---
I have recently made a program that finds the sum of all primes (they are 11)
that truncable from left to right and from right to left.
I compiled it with -O -release -inline -noboundscheck
The results were:
I made a few changes to make it compile as C code, and compiled in gcc with -O5
-lm -std=c99. The results:
There's ~900 ms difference here, which is big.
The problem is in a function I used, "isPrime(ulong)"
/// returns true if n is a prime number
bool isPrime(ulong n)
// 0 and 1 aren't primes
if( n < 2 ) return false;
if( n % 2 == 0 && n != 2)
return false; // an even number can't be a prime (except 2)
// check only if it's odd
for(ulong i = 2; i <= cast (ulong)sqrt(cast(double)n+1); ++i)
if( n % i == 0 )
As you can see, in the for loop, sqrt() is called in every iteration and that's
what makes it slower. When changed to:
ulong limit = cast (ulong)sqrt(cast(double)n+1)
for(ulong i = 2; i <= limit; ++i)
It performs in 400ms!!!
Somehow the C version manages to do that sort of optimizations. I expect DMD to
do it as well, as it makes the code A LOT faster.
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------