OpenMP计算每个线程的循环迭代次数

OpenMP count the number of iteration in cycle which is making each thread

本文关键字:循环 迭代 线程 计算 OpenMP      更新时间:2023-10-16

我决定计算每个线程的循环迭代次数。所以我必须声明变量并得到每个迭代的线程数,对吗?我得到了线程数就像(0,1,2,3)4个线程。但是,当我创建变量来计算每个线程的总和时,我遇到了一个问题。

#include <iostream>
#include <time.h>
#include <math.h>
#include "fact.h"
#include <cstdlib>;
#include <conio.h>;
#include <omp.h>
using namespace std;
int main()
{
clock_t t1,t2;
int n;
long double exp=0;
long double y;
int p;
int axe;
cout<<"Enter n:";
cin>>n;
t1=clock();
int a=0,b=0,c=0,d=0;
    #pragma omp parallel for num_threads(4) reduction (+:exp)
for(int i=1; i<n; i++)
{
        int l=omp_get_thread_num();
        cout<<l<<endl;
        if (l=0) {a++;}
        else if (l=1) {b++;}
        else if (l=2) {c++;}
        else   {d++;}


p=i+1;
    exp=exp+(1/((fact(p))));
}
t2=clock();
double total_clock;
total_clock=t2-t1;
long double total_exp;
total_exp=exp+2;
cout<<endl;
cout<<endl;
cout<<total_clock<<"t the time is used for parralel calculations"<<endl;
cout<<total_exp<<endl;
cout<<a<<" thread one"<<endl;
cout<<b<<"thread two"<<endl;
cout<<c<<"thread three"<<endl;
cout<<d<<"Thread fourth"<<endl;
    return 0;}

我没有得到错误,但它告诉我不是每个线程正在制作的循环迭代的适当数量。在这项工作中,我计算了指数。2.71

您需要使用if (l == 0)等代替if (l = 0)。后者将0赋给l,而不是将l比较为0。