我使用OpenMP在C中编写了一个代码,但编译时的前四个结果总是以不同的顺序运行,并且运行时间仅在大约一半的时间内显示非0的值。我错过了什么吗?这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
void test(int *ptr0, int *ptr1, int n)
{
int sum=0, i;
int id=omp_get_thread_num();
for(i=0;i<16;i++){
sum+=prt0[i]*ptr1[i];
}
printf("Sum = %d from thread %d\n",sum,id);
}
int main()
{
int m=64, n=16, a, b;
int** array0=calloc(m, sizeof(int*));
for(a=0;a<m;a++){
array0[a]=calloc(n, sizeof(int));
}
int** array1=calloc(m, sizeof(int*));
for(b=0;b<m;b++){
array1[b]=calloc(n, sizeof(int));
}
for(i=0;i<16;i++);{
array0[i][n/2]=i;
array1[i][n/2]=i;
}
#pragma omp parallel for schedule(dynamic)
for(i=0;i<n;i++){
test(array0[i],array1[i],n);
}
double start_time, run_time;
start_time=omp_get_wtime();
run_time=omp_get_wtime()-start_time;
printf("Total run time = %.5g seconds\n", run_time);
}
结果是(前4行的不同变化):
Sum = 0 from thread 3
Sum = 1 from thread 1
Sum = 4 from thread 2
Sum = 9 from thread 3
Sum = 16 from thread 0
Sum = 25 from thread 1
Sum = 36 from thread 2
Sum = 49 from thread 3
Sum = 64 from thread 0
Sum = 81 from thread 1
Sum = 100 from thread 2
Sum = 121 from thread 3
Sum = 144 from thread 0
Sum = 169 from thread 1
Sum = 196 from thread 2
Sum = 225 from thread 3
Total run time = 3.95e-07 seconds
关于如何使结果与总和为0,1,4,9等以及运行时间不是0秒的任何建议?
答案 0 :(得分:0)
为什么期望通过请求当前启动和放大来保持较长的持续时间?在行结束时间?你不想测量什么吗?我想你的真正目标是在循环开始之前得到开始时间,在完成所有测试之后得到结束时间。
您无法控制输出的顺序,因为您的线程运行速度失控。只需将结果放在一个额外的数组中,然后在主线程中打印内容。