【发布时间】:2011-07-10 00:16:46
【问题描述】:
我正在尝试在 C 中并行化光线追踪器,但执行时间并没有随着线程数量的增加而下降。我到目前为止的代码是:
main2(thread function):
float **result=malloc(width * sizeof(float*));
int count=0;
for (int px=0;, px<width; ++px)
{
...
for (int py=0; py<height; ++py)
{
...
float *scaled_color=malloc(3*sizeof(float));
scaled_color[0]=...
scaled_color[1]=...
scaled_color[2]=...
result[count]=scaled_color;
count++;
...
}
}
...
return (void *) result;
main:
pthread_t threads[nthreads];
for (i=0;i<nthreads;i++)
{
pthread_create(&threads[i], NULL, main2, &i);
}
float** result_handler;
for (i=0; i<nthreads; i++)
{
pthread_join(threads[i], (void *) &result_handler);
int count=0;
for(j=0; j<width;j++)
{
for(k=0;k<height;k++)
{
float* scaled_color=result_handler[count];
count ++;
printf...
}
printf("\n");
}
}
main2 返回一个float **,以便在main函数中按顺序打印图片。任何人都知道为什么执行时间没有下降(例如,当它应该是相反的方式时,它使用 8 个线程比使用 4 个线程运行的时间更长)?
【问题讨论】:
-
添加线程并不会神奇地让您的计算机更快...您还没有指定您拥有多少个内核,除非您至少有 8 个,否则 8 个计算密集型线程会减慢您的速度管理和切换线程的开销。
-
...并可能导致更多的缓存未命中,进一步减慢速度。
标签: c parallel-processing