开发者

Fast Random Generator

How can I make a fast RNG (Random Number Generator) in C# that support filling an array of bytes with a maxValue (and/or a minValue)? I have found this http://www.c开发者_Python百科odeproject.com/KB/cs/fastrandom.aspx but doesn't have these feature.


The fact that you're filling bytes with integers is different enough from the typical usage case for System.Random that you can probably beat it badly if you really need to.

System.Random is made for general use. (In fact, I usually find system random routines uninspiring when I do speed and distribution tests on them.) There are cases where you'd want something else. But you have to be very explicit about your needs. How fast? What are you willing to give up?

If you really need "fast," Marsaglia has produced a number of very fast random number generators that could be adapted to your needs. Here are a few links about one of them, Xorshift:

  • Xorshift (Wikipedia)
  • Fastest implementation of Xorshift in C#, and measurements comparing it to System.Random
  • The Diehard tests are interesting.
  • Agner has C++ code for many fast randoms.
  • Here's a fast twister that uses SIMD instructions.

The last one addresses the fact that you are targeting bytes.

I've only needed super fast randoms a few times. In console games with slow processors where random could make the difference between hitting the frame rate target and not hitting it. What is your use case? By all means, use System.Random if you can.

Or, adapt the routine you link to in your question (which the author claims is 8x the speed of System.Random.)


System.Random is fast enough for just about any typical use. If you're having performance issues with code that contains System.Random calls, make sure you profile your code before trying to build a new Random. Chances are your performance issues are not in the framework, but rather in your own code.

If you're calling into Random in a loop, make sure you're not creating a new Random instance with each iteration, but instead are re-using a common Random instance. Doing this will improve performance because you aren't creating new objects for the GC to clean up, and will also improve the quality of the random numbers being generated.


If you have a random number generator that returns numbers from the unit interval, like the one in the Code Project article you mentioned, then you can first generate a value u using that generator and then return a + (b-a)*u to get values between a and b.


use the cryptographic services....

RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
byte[] bytes= new byte[5];
crypto.GetBytes(bytes);

of course, this only satisfies the byte area requirement...


You could use Reflector to decompile System.Random to C#. That would give you the C# code of a fast random number generator that fulfills your requirements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜