[fpc-pascal] for loop vs while loop
Mark Morgan Lloyd
markMLl.fpc-pascal at telemetry.co.uk
Thu Feb 2 10:01:52 CET 2017
On 01/02/17 20:30, Nitorami wrote:
> Just a note - I learned that for very short "for" loops it may be even a bit
> faster to count downwards (to zero) rather than upwards if possible, because
> the comparison to zero is very effiicient. Not sure though whether that
> still makes a difference on modern processors.
Testing that on fpc 3.0.0 x86, compiled with -O4 but without looking at
the generated code:
program test1;
const top = $7fffffff;
var a, i: longint;
begin
for i := 0 to top do
a := i;
writeln(a)
end.
real 0m4.353s
user 0m3.284s
sys 0m0.000s
program test2;
for i := top downto 0 do
a := i;
real 0m4.449s
user 0m3.256s
sys 0m0.000s
program test3;
for i := top downto 0 do
a := top - i;
real 0m4.671s
user 0m3.264s
sys 0m0.000s
It's interesting that the real (wallclock) and user times are
consistently in a different sequence. /If/ the user time is to be
believed, there's a very small advantage to counting down even if the
sequence you want is ascending (i.e. test3) rather than simply counting up.
--
Mark Morgan Lloyd
markMLl .AT. telemetry.co .DOT. uk
[Opinions above are the author's, not those of his employers or colleagues]
More information about the fpc-pascal
mailing list