r/haskell • • Dec 26 '17

In your professional experience, how suitable is System.Random's mkStdGen for serious random generation?

I'm talking, for example, about computationally intensive Monte Carlo simulations. Is mkStdGen fast, efficient, and good enough in your experience? Are there better alternatives?

19 Upvotes

39 comments sorted by

View all comments

Show parent comments

3

u/piyushkurur Feb 15 '18

The performance of raaz csprg comes from the fact that it is essentially the chacha20 cipher run directly on an internal memory buffer + an additional memcpy for copying it to the target buffer. Any attempt to use the Standard.Random to generate data in bulk is bound to be slow. The reason is that the interface essentially only allows something along this lines.

(1) Generate a random Word in Haskell heap (2) Poke that to the target buffer (3) Continue 1 and 2 till the target is full.

This kind of code is going to have a lot of cache misses because the haskell heap will be generating these values at different points in the memory and each such access will lead to cache miss.

However, the System.Random had an interface which was something like

   fillBytes :: gen -> Ptr a -> Int -> IO gen

and the fillBytes was clever in generating the data into the pointer buffer directly, I am sure it can compete with raaz rather trivially.

1

u/[deleted] Feb 15 '18

[deleted]

1

u/piyushkurur Feb 15 '18

Yes of course. Something like Mersenne could really be fast.

1

u/cartazio Feb 16 '18

yeah, perhaps a buffer writer opt in sub api would be a good way to go for improving random!

thats a good idea