[fpc-pascal] Why is Random(255) some 529x slower compared to Delphi 7?

michael.vancanneyt at wisa.be michael.vancanneyt at wisa.be
Wed Dec 7 13:51:36 CET 2011



On Wed, 7 Dec 2011, Graeme Geldenhuys wrote:

> Hi,
>
> I'm busy working on some of the remaining unit tests for the tiOPF
> project that doesn't run 100% to my satisfaction yet under FPC
> (compared to Delphi 7). One of the tests is for a Simple Encryption
> algorithm implemented in tiOPF, that runs extremely slow under FPC
> 2.4.x (and 2.6.0-rc), and near instant under Delphi 7. I'm trying to
> figure out why.
>
> Below is a snippet of code I tracked down which contains the slowdown.
> The problem under FPC lies with line 08, and more specifically the
> call to Random(255). Simply replacing the Random(255) call with a
> variable speeds up the loop by some 529 times!
>
> I did a simple GetTickCount() timing around this loop. Delphi executes
> the loop in 20 ticks. FPC 2.6.0-rc2 takes 10585 ticks!!!! The outer
> loop runs 200400 iterations. The types for BitValue, ByteValue and
> RandSeed is of type Byte.
>
> 01  for Index := 1 to Length(Source) do
> 02  begin
> 03    OrdValue := Ord(Source[Index]);
> 04    for BitCount := 0 to 7 do
> 05    begin
> 06      BitValue := Byte(OrdValue and (1 shl BitCount) = 1 shl BitCount);
> 07      RandSeed := ByteValue;
> 08      ByteValue := (((Random(255) + 1) div 2) * 2) + BitValue;
> 09      Result[(Index - 1) * 8 + BitCount + 1] := AnsiChar(ByteValue);
> 10    end;
> 11  end;
>
> I'm using 64bit Ubuntu Linux 10.04.3 with 64-bit FPC 2.6.0-rc2.
> Anybody have any ideas why the code under FPC runs so slowly? Is it
> maybe some type conversion problem in FPC? I noticed that Random()
> returns a Int64 on my Linux system. I'm not sure what it returns under
> Delphi 7 (the docs don't say, and I can see the implementation of it).

I think the random() algorithm is simply much more complicated in FPC.
It tries very hard to get an evenly distributed random number, more so 
than Delphi, probably.

Jonas Maebe implemented it, I think, he can probably shed some more light on
this.

Michael.



More information about the fpc-pascal mailing list