相关疑难解决方法(0)

多线程random_r比单线程版本慢

以下程序与此处描述的程序基本相同.当我使用两个线程(NTHREADS == 2)运行并编译程序时,我得到以下运行时间:

real        0m14.120s
user        0m25.570s
sys         0m0.050s
Run Code Online (Sandbox Code Playgroud)

当它只用一个线程(NTHREADS == 1)运行时,即使它只使用一个核心,我的运行时间也会明显更好.

real        0m4.705s
user        0m4.660s
sys         0m0.010s
Run Code Online (Sandbox Code Playgroud)

我的系统是双核的,我知道random_r是线程安全的,我很确定它是非阻塞的.当没有random_r运行相同的程序并且使用余弦和正弦的计算作为替换时,双线程版本按预期运行大约1/2.

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

#define NTHREADS 2
#define PRNG_BUFSZ 8
#define ITERATIONS 1000000000

void* thread_run(void* arg) {
    int r1, i, totalIterations = ITERATIONS / NTHREADS;
    for (i = 0; i < totalIterations; i++){
        random_r((struct random_data*)arg, &r1);
    }
    printf("%i\n", r1);
}

int main(int argc, char** argv) {
    struct random_data* rand_states = (struct random_data*)calloc(NTHREADS, sizeof(struct random_data));
    char* rand_statebufs = …
Run Code Online (Sandbox Code Playgroud)

c linux random performance multithreading

10
推荐指数
1
解决办法
2972
查看次数

标签 统计

c ×1

linux ×1

multithreading ×1

performance ×1

random ×1