Fast Random Generator

2019-04-05 15:21发布

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.codeproject.com/KB/cs/fastrandom.aspx but doesn't have these feature.

标签: c# random
5条回答
smile是对你的礼貌
2楼-- · 2019-04-05 15:58

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.

查看更多
叛逆
3楼-- · 2019-04-05 16:01

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...

查看更多
神经病院院长
4楼-- · 2019-04-05 16:08

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:

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.)

查看更多
我想做一个坏孩纸
5楼-- · 2019-04-05 16:17

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.

查看更多
The star\"
6楼-- · 2019-04-05 16:20

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.

查看更多
登录 后发表回答