✅ Faster & thread safe random number generator?

Is there a good library for getting pseudo random numbers, faster than System.Random? I've done some looking but had a hard time coming up with much.
37 Replies
Angius
Angius2mo ago
Do you find the speed of System.Random a bottleneck?
MechWarrior99
MechWarrior992mo ago
Yeah, not a massive one, but definitely is one.
Angius
Angius2mo ago
Are you using multiple instances of Random, or Random.Shared? Or some singleton you yourself made
MechWarrior99
MechWarrior992mo ago
I have a large process which I create a new instance of Random for each time, since the process runs in a Task in a separate thread.
Angius
Angius2mo ago
Random.Shared is thread-safe, IIRC
ParaLogia
ParaLogia2mo ago
Random.Shared Property (System)
Provides a thread-safe Random instance that may be used concurrently from any thread.
MODiX
MODiX2mo ago
Angius
REPL Result: Success
using System;
using System.Threading.Tasks;

Parallel.For(0, 10, x =>
{
var value = Random.Shared.Next();
Console.WriteLine(value);
});
using System;
using System.Threading.Tasks;

Parallel.For(0, 10, x =>
{
var value = Random.Shared.Next();
Console.WriteLine(value);
});
Console Output
1562793860548352853
252507751
1548914677
1900456204
1478899365
11502557
1227585618
1038092387

1986991436
1562793860548352853
252507751
1548914677
1900456204
1478899365
11502557
1227585618
1038092387

1986991436
Compile: 356.154ms | Execution: 96.933ms | React with ❌ to remove this embed.
Angius
Angius2mo ago
Well this got one empty line lmao Could just be Modix though
MechWarrior99
MechWarrior992mo ago
Ah good to know, but I actually reset the seed each time, which is why I create a new instance each time.
Angius
Angius2mo ago
You need deterministic random?
MechWarrior99
MechWarrior992mo ago
Yeah
Angius
Angius2mo ago
Then I don't think you'll get much faster than System.Random Though you can always look for some nugers Maybe there's something that provides slightly worse randomness but is more performant I only know a less-performant way, RandomNumberGenerator, but this one's cryptographically secure
MechWarrior99
MechWarrior992mo ago
Yeah I don't really mind if it is a bit worse randomness (I think at least haha)
ParaLogia
ParaLogia2mo ago
xkcd: Random Number
From An unknown user
RFC 1149.5 specifies 4 as the standard IEEE-vetted random number.
MechWarrior99
MechWarrior992mo ago
I remember seeing something about using xor-shift to get random numbers, but couldn't find a lot on it. 🤔
Want results from more Discord servers?
Add your server