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.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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.
use the cryptographic services....
of course, this only satisfies the byte area requirement...
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.)
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 returna + (b-a)*u
to get values between a and b.