Division
by: G.E. Ozz Nixon Jr.
Published: August 2009
©opyright 2009 by Friends of FPC
While working on a couple optimization examples for you guys, I realized we have been taught to use "div" to
to division when possible over "/". As "div" has been optimized for whole numbers where as "/" was designed
to handle both whole numbers and fractions. So, I decided to write a quick and dirty test application to see
if this still holds true today. In short, yes on a Mac, no on Linux... here is my test code:
Download division.pas source
Uses
dxutil_environment;// contains TimeCounter for Windows, Linux and Mac
Var
Loop:LongWord;
StartTime:Comp;
X:Longint;
Y:Extended;
Begin
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do X:=SizeOf(LongWord) div 2;
System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));
StartTime:=Trunc(TimeCounter);
For Loop:=1 to 100000000 do Y:=SizeOf(LongWord) / 2;
System.Writeln(Trunc(Trunc(TimeCounter)-StartTime));
end.
Oddly (over 100 million calls), on the Mac OS X div took 199ms and "/" took 520ms. However, on
this web server (Linux) the code above takes 332ms for "div" and only 225ms for "/". There are many reasons I can assume
of why the drastic difference on the Mac. However, the difference between the Mac and Linux is actually confusing. As I
thought, on the Mac is is due to the "Extended" variable type. When I changed that to "real" and ran the code again, the
"/" theory only took 392ms. See my next experiment titled fraction variables... I will take this thought to document type(s).
G.E. Ozz Nixon Jr.