rand()
is quite slow on modern GNU/Linux compared to a good modern PRNG. The Glibc implementation takes/releases a lock even in a single-threaded program. (To see this, compile a program like int main(){return rand();}
with gcc -g -fno-plt
and stepi
into the call rand
in GDB.)
Internally, Glibc rand()
calls random()
, which takes a lock and then calls random_r()
on seed shared between all threads. The locking doesn't special-case for programs that haven't been linked with libpthread
, so despite the PRNG being pretty simple, it's not fast either.
If you care at all about speed in a program that needs a lot of random numbers, either use your own PRNG (like xoroshiro), or use random_r
with your own state variable, although the API for initializing it is not ideal as the man page notes. Or there's long mrand48()
which in glibc avoids taking a lock, which returns a value in [-2^31, +2^31)
(signed int32_t), although its not the best PRNG.