dimanche 28 mai 2017

Why rand() is much faster than arc4random()

I'm writing a game AI which requires fast int random number generation. This game is for Mac OS, so there are two choices rand() (the plain C) and arc4random() (BSD). I didn't find any comparison in speed for these two functions, so I wrote a small program to test:

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.

I tested several times. Results are quite stable: srand() and 999999999 iterations of rand() takes around 6 s, while arc4random() takes much longer (around 30 s).

Is there any reason that arc4random() takes much longer time? Or is there any flaw in my testing. Thank you!




Aucun commentaire:

Enregistrer un commentaire