每当我运行此代码时,它都会向我显示并行部分所花费的不同运行时间。我根据我的核心尝试使用恒定数量的线程,但努力仍然是徒劳的。该程序是计算 pi 的值。使用gcc -fopenmp
编译。
#include <stdio.h>
#include <omp.h>
static long num_steps = 100000; double step;
//double omp_get_wtime(void);
int main (){
int i;
double x,pi,max_threads,start,time;
double sum=0.0;
step = 1.0/(double) num_steps;
//omp_set_num_threads(4);
omp_get_max_threads();
start=omp_get_wtime();
#pragma omp parallel
{
#pragma omp for reduction(+:sum) schedule(static) private(x) //reduction to get local copy
for (i=0;i<num_steps;i++){
x=(i+0.5)*step;
sum += 4.0/(1.0+x*x);
}
//max_threads=omp_get_max_threads();
}
time=omp_get_wtime()-start;
pi=step*sum;
printf("pi=(%f)\t run_time(%f)\n",pi,time);//,max_threads);
return 0;
}
最佳答案
该代码仅运行几毫秒(在我的系统上为 2-6 毫秒),时间主要是开销,例如用于线程创建。串行版本的运行时间<1 毫秒。如此短的执行时间变化很大是正常的,因为它取决于系统的当前状态,例如有一些“需要热身”。
在这种情况下,只需增加 num_steps
即可获得有意义的稳定结果。例如。当 num_steps = 1000000000
时,在我的系统上执行 10 次的时间都在 4.332 到 4.399 秒之间。
通常,如果您进行性能测量,则应使用 -O3
标志进行编译。
关于c - OpenMP 并行区域的不同运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42365240/