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

前端 未结 4 1855
栀梦
栀梦 2020-12-13 06:17

I\'m trying around on the new C++11 threads, but my simple test has abysmal multicore performance. As a simple example, this program adds up some squared random numbers.

4条回答
  •  眼角桃花
    2020-12-13 06:39

    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;
    }
    

提交回复
热议问题