【发布时间】:2011-03-01 08:05:33
【问题描述】:
以下程序与here 描述的程序基本相同。当我使用两个线程 (NTHREADS == 2) 运行和编译程序时,我得到以下运行时间:
real 0m14.120s
user 0m25.570s
sys 0m0.050s
当它仅使用一个线程 (NTHREADS == 1) 运行时,即使它仅使用一个内核,我的运行时间也会显着提高。
real 0m4.705s
user 0m4.660s
sys 0m0.010s
我的系统是双核的,我知道 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 = (char*)calloc(NTHREADS, PRNG_BUFSZ);
pthread_t* thread_ids;
int t = 0;
thread_ids = (pthread_t*)calloc(NTHREADS, sizeof(pthread_t));
/* create threads */
for (t = 0; t < NTHREADS; t++) {
initstate_r(random(), &rand_statebufs[t], PRNG_BUFSZ, &rand_states[t]);
pthread_create(&thread_ids[t], NULL, &thread_run, &rand_states[t]);
}
for (t = 0; t < NTHREADS; t++) {
pthread_join(thread_ids[t], NULL);
}
free(thread_ids);
free(rand_states);
free(rand_statebufs);
}
我很困惑为什么在生成随机数时两个线程版本的性能比单线程版本差得多,考虑到 random_r 旨在用于多线程应用程序。
【问题讨论】:
标签: c linux performance multithreading random