C# 生成随机布尔值的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19191058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to generate a random boolean
提问by timedt
So there is several ways of creating a random bool in C#:
所以在 C# 中有几种创建随机布尔值的方法:
- Using Random.Next():
rand.Next(2) == 0
- Using Random.NextDouble():
rand.NextDouble() > 0.5
- 使用 Random.Next():
rand.Next(2) == 0
- 使用 Random.NextDouble():
rand.NextDouble() > 0.5
Is there really a difference? If so, which one actually has the better performance? Or is there another way I did not see, that might be even faster?
真的有区别吗?如果是这样,实际上哪个性能更好?或者还有另一种我没有看到的方式,那可能会更快?
采纳答案by Aviran Cohen
The first option- rand.Next(2)
executes behind the scenes the following code:
第一个选项-rand.Next(2)
在幕后执行以下代码:
if (maxValue < 0)
{
throw new ArgumentOutOfRangeException("maxValue",
Environment.GetResourceString("ArgumentOutOfRange_MustBePositive", new object[] { "maxValue" }));
}
return (int) (this.Sample() * maxValue);
and for the second option- rand.NextDouble()
:
对于第二个选项- rand.NextDouble()
:
return this.Sample();
Since the first option contains maxValue
validation, multiplication and casting, the second option is probably faster.
由于第一个选项包含maxValue
验证、乘法和强制转换,因此第二个选项可能更快。
回答by DaRich
Small enhancement for the second option:
第二个选项的小改进:
According to MSDN
根据MSDN
public virtual double NextDouble()
returns
返回
A double-precision floating point number greater than or equal to 0.0, and less than 1.0.
大于或等于 0.0 且小于 1.0 的双精度浮点数。
So if you want an evenly spread random bool you should use >= 0.5
所以如果你想要一个均匀分布的随机布尔值,你应该使用 >= 0.5
rand.NextDouble() >= 0.5
Range 1: [0.0 ... 0.5[
Range 2: [0.5 ... 1.0[
|Range 1| = |Range 2|
范围 1:[0.0 ... 0.5[
范围 2:[0.5 ... 1.0[
|范围 1|] = |范围 2|
回答by Frederik Steinmetz
I ran tests with stopwatch. 100,000 iterations:
我用秒表进行了测试。100,000 次迭代:
System.Random rnd = new System.Random();
if (rnd.Next(2) == 0)
trues++;
CPUs like integers, so the Next(2) method was faster. 3,700 versus 7,500ms, which is quite substantial. Also: I think random numbers can be a bottleneck, I created around 50 every frame in Unity, even with a tiny scene that noticeably slowed down my system, so I also was hoping to find a method to create a random bool. So I also tried
CPU 喜欢整数,所以 Next(2) 方法更快。3,700 与 7,500 毫秒,这是相当可观的。另外:我认为随机数可能是一个瓶颈,我在 Unity 中每帧创建了大约 50 个,即使是一个明显减慢我系统速度的小场景,所以我也希望找到一种方法来创建一个随机布尔值。所以我也试过
if (System.DateTime.Now.Millisecond % 2 == 0)
trues++;
but calling a static function was even slower with 9,600ms. Worth a shot. Finally I skipped the comparison and only created 100,000 random values, to make sure the int vs. double comparison did not influence the elapsed time, but the result was pretty much the same.
但是调用静态函数甚至更慢,为 9,600 毫秒。值得一试。最后我跳过了比较,只创建了 100,000 个随机值,以确保 int 与 double 比较不会影响经过的时间,但结果几乎相同。
回答by Theodor Zoulias
The fastest.Calling the method Random.Next
has the less overhead. The extension method below runs 20% faster than Random.NextDouble() > 0.5
, and 35% faster than Random.Next(2) == 0
.
最快的。调用该方法Random.Next
的开销较小。下面的扩展方法运行速度比 快 20%,比Random.NextDouble() > 0.5
快 35% Random.Next(2) == 0
。
public static bool NextBoolean(this Random random)
{
return random.Next() > (Int32.MaxValue / 2);
// Next() returns an int in the range [0..Int32.MaxValue]
}
Faster than the fastest.It is possible to generate random booleans with the Random
class even faster, by using tricks. The 31 significant bits of a generated int
can be used for 31 subsequent boolean productions. The implementation bellow is 40% faster than the previously declared as the fastest.
比最快的还快。Random
通过使用技巧,可以更快地使用该类生成随机布尔值。生成的 31 个有效位int
可用于 31 个后续布尔产生式。下面的实现比之前宣布的最快的要快 40%。
public class RandomEx : Random
{
private uint _boolBits;
public RandomEx() : base() { }
public RandomEx(int seed) : base(seed) { }
public bool NextBoolean()
{
_boolBits >>= 1;
if (_boolBits <= 1) _boolBits = (uint)~this.Next();
return (_boolBits & 1) == 0;
}
}