我想知道每个线程在for循环中使用了多少时间。我希望time_taken对于每个线程都是私有的,以便他们可以在那里添加自己的时间。最好的转换,我想要每个线程的总时间,而不是while循环中每次迭代的时间。
double time_taken = 0.0;
while(delta >= epsilon) {
delta = 0.0;
double wtime = omp_get_wtime();
#pragma omp parallel for reduction(+:delta)
for (i = 0; i < workSize; i++) {
#do some work and change delta
}
time_taken += omp_get_wtime() - wtime
printf("time taken by thread %d: %f\n", omp_get_thread_num(), time_taken);
}
我试图像这样在while循环中设置time_taken私有:
double time_taken = 0.0;
while(delta >= epsilon) {
delta = 0.0;
#pragma omp private(time_taken)
{
double wtime = omp_get_wtime();
#pragma omp parallel for reduction(+:delta)
for (i = 0; i < workSize; i++) {
#do some work and change delta
}
time_taken += opm_get_wtime() - wtime
printf("time taken by thread %d: %f\n", omp_get_thread_num(), time_taken);
}
}
我也研究了使用threadprivate
,但我不知道如何正确使用它。
答案 0 :(得分:0)
您可以尝试以下代码。这样会分配一个大小等于线程数的指针数组,然后每个线程都会分配私有内存,即没有错误共享。
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
double delta = 20, epsilon = 0;
double **time_taken;
omp_set_dynamic(0);
#pragma omp parallel
{
int it = omp_get_thread_num();
#pragma omp single
time_taken = malloc(sizeof *time_taken * omp_get_num_threads());
time_taken[it] = malloc(sizeof *time_taken[omp_get_thread_num()]);
*time_taken[it] = 0.0;
}
double sum = 0;
while(delta >= epsilon) {
#pragma omp parallel
{
int it = omp_get_thread_num();
*time_taken[it] -= omp_get_wtime();
#pragma omp for reduction(+: sum)
for(int i= 0 ; i<2000000000; i++) sum += 1.0*i, delta -=1;
*time_taken[it] += omp_get_wtime();
}
}
printf("sum %f\n", sum);
#pragma omp parallel
{
int it = omp_get_thread_num();
printf("time taken by thread %d: %f\n", it, *time_taken[it]);
free(time_taken[omp_get_thread_num()]);
#pragma omp barrier
#pragma omp single
free(time_taken);
}
}