【发布时间】:2021-06-17 08:25:23
【问题描述】:
对于以下代码,我计算了每个线程的执行时间,但奇怪的是,在我使用静态或动态调度进行的所有运行中,每个线程都有几乎准确的时间调用。这是 OpenMP 中预期的吗?我们是否曾经遇到过一个或多个线程执行更多工作的情况? 我不明白的另一件事是使用静态和动态计划的时间执行是相同的。恐怕我计算时间的方式不对。
#include <iostream>
#include <vector>
#include <random>
#include <cmath>
#include <omp.h>
#include <fstream>
#include <cfloat>
#include <chrono>
using namespace std;
using namespace chrono;
int main()
{
const int N = 100000;
ofstream result{"Result.txt"};
vector<vector<double>> c;
default_random_engine g(0);
uniform_real_distribution<double> d(0.0f, nextafter(1.0f, DBL_MAX));
c.reserve(N);
for (int i = 0; i < N; i++) {
const unsigned size = pow(10, i % 4);
vector<double> a;
a.reserve(size);
for (int j = 0; j < size; j++) {
const double number = d(g);
a.push_back(number);
}
c.push_back(std::move(a));
}
double sum = 0.0;
vector<double> b(N);
int total_threads=4;
double time_taken_by_threads[total_threads];
auto t1= high_resolution_clock::now();
#pragma omp parallel num_threads(4) firstprivate(N) shared(b,c,sum)
{
int threadID = omp_get_thread_num();
double start = omp_get_wtime();
#pragma omp for reduction(+:sum) schedule(dynamic)
for (int i = 0; i < N ; i++) {
double sumLocal = 0.0;
for (int j = 0; j < c[i].size();j++) {
sumLocal += pow(c[i][j], 2);
}
const double n = sqrt(sumLocal);
b[i] = n;
sum += sumLocal;
}
double end = omp_get_wtime();
time_taken_by_threads[threadID] = end - start;
}
auto t2=high_resolution_clock::now();
auto diff=duration_cast<milliseconds>(t2-t1);
cout<<"The total job has been taken : "<<diff.count()<<endl;
for(int i=0; i<total_threads ; i++){
cout<<" Thread work "<< time_taken_by_threads[i]<<endl;
}
}
【问题讨论】:
标签: c++ multithreading performance parallel-processing openmp