Why is this C++11 code containing rand() slower with multiple threads than with one? Why is this C++11 code containing rand() slower with multiple threads than with one? multithreading multithreading

Why is this C++11 code containing rand() slower with multiple threads than with one?


On my system the behavior is same, but as Maxim mentioned, rand is not thread safe. When I change rand to rand_r, then the multi threaded code is faster as expected.

void add_multi(int N, double& result) {double sum=0;unsigned int seed = time(NULL);for (int i = 0; i < N; ++i){    sum+= sqrt(1.0*rand_r(&seed)/RAND_MAX);}result = sum/N;}


As you discovered, rand is the culprit here.

For those who are curious, it's possible that this behavior comes from your implementation of rand using a mutex for thread safety.

For example, eglibc defines rand in terms of __random, which is defined as:

long int__random (){  int32_t retval;  __libc_lock_lock (lock);  (void) __random_r (&unsafe_state, &retval);  __libc_lock_unlock (lock);  return retval;}

This kind of locking would force multiple threads to run serially, resulting in lower performance.


The time needed to execute the program is very small (33msec). This means that the overhead to create and handle several threads may be more than the real benefit. Try using programs that need longer times for the execution (e.g., 10 sec).