Page 1 of 1

Fast int64 mod and div in Delphi.

Posted: Mon Mar 26, 2007 9:36 pm
by hk
Delphi's int64 mod and div are extremely slow compared with timings in C.
While developing problem problem 146 we discovered a nice work around:

Suppose n is a int64 variable
instead of eg: k:=n div p we can write k:=trunc(n/p).
instead of eg: k:=n mod p we can write k:=n-trunc(n/p)*p
This is about 5 times as fast and comparable to timings in C.

Posted: Sun Apr 01, 2007 5:22 pm
by ThomasH
Thank you very much for the workaround: in problem 146, I have one mod operation working on an int64 in the main loop. The runtime was 20 seconds. Replacing n mod p with n-trunc(n/p)*p resulted in dropping the runtime to 7 seconds.

I am using Delphi4 under XP. I tried some timing also in Delphi2005 and apparently the div operation there is faster than the trunc(..) replacement, but the mod operation is as slow as in Delphi4 (working on int64 and filled with a number larger than maxint).

Posted: Thu Apr 05, 2007 4:31 pm
by Hui
Hi, I made some timing-experiments, too.

I'm using free Delphi2005 on a P4 and found that while numbers are smaller than MaxInt the div and mod operations are quicker, if they are bigger, there is no difference with div but mod-operations are about twice as fast when I'm going your way. Much to optimize for the Borlanders, I think.

BTW, I found that using TBits instead of array of Boolean makes a primes-sieve twice as quick.

Greetings Hui

edit: much quicker mod (for me): Frac(n/p)*p