我正在编写一个需要快速整数随机数生成的游戏人工智能。该游戏适用于Mac OS,因此有两种选择rand()(纯C)和arc4random()(BSD)。我没有发现这两个函数在速度上有任何比较,所以我写了一个小程序来测试:
long i;
// Record timestamp here.
srand((unsigned int)time(NULL));
for (i = 0; i < 999999999; ++i) {
rand();
}
// Record timestamp here.
for (i = 0; i < 999999999; ++i) {
arc4random();
}
// Record timestamp here and print all three.
Run Code Online (Sandbox Code Playgroud)
我测试了好几次。结果相当稳定:srand()999999999次迭代rand()大约需要6秒,而arc4random()需要更长的时间(大约30秒)。
有什么原因arc4random()需要更长的时间吗?或者我的测试有什么缺陷。谢谢你!