Speed of Random Numbers

bauss jj_1337 at live.dk
Sat Aug 3 19:23:36 UTC 2019


On Saturday, 3 August 2019 at 17:47:46 UTC, Giovanni Di Maria 
wrote:
> On Saturday, 3 August 2019 at 17:44:44 UTC, lithium iodate 
> wrote:
>> On Saturday, 3 August 2019 at 16:35:34 UTC, Giovanni Di Maria 
>> wrote:
>>> [...]
>>
>> First off you could try to use a faster RNG engine than the 
>> default. The easiest way is to define a variable containing it 
>> and passing it to the functions each time.
>>
>> auto rng = Xorshift(1234);
>> randomNumber = uniform!uint(rng);
>>
>> This basic change approximately halved the 5 seconds your 
>> original example needs on my computer.
>> Another simple approach that I have tried is simply hashing 
>> the iterator using a fast hash function.
>> With xxHash32 I got the time down to 0.25 seconds. I also 
>> tried xxHash64 and FNV1a but they were not faster in my quick 
>> test.
>
>
>
> Thank you very much Lithium Iodate
> Now i will try it.
> I let know you.
> Thank you
> Giovanni

If it doesn't matter if it's predictable or not then you could 
easily make your own simple random generator with would give 
"random" results.

Of course in general it's not usable:

import std.stdio;

class Random
{
     private:
     uint _seed;
     uint _interval;

     T abs(T)(T x)
     {
         T y = x > 0 ? T.max : cast(T)0;

         return (x ^ y) - y;
     }

     public:
     this()
     {
         import core.stdc.time;

         _seed = cast(uint)time(null);
         _interval = (_seed - 20559);
     }

     T next(T)(T max)
     {
         auto value = cast(T)(abs(_interval) % T.max);

         _interval -= (_interval / 10) * _seed;

         return value;
     }
}

void main()
{
     auto random = new Random;

     foreach (_; 0 .. 1000)
     {
         auto result = random.next!ubyte(255);
         writeln(result);
     }
}




More information about the Digitalmars-d-learn mailing list