首页 > 解决方案 > 为什么我的代码使用 OpenMP 比不使用 OpenMP 需要更长的时间?

问题描述

我是 OpenMP 的新手,正在尝试学习如何使用它。我使用以下代码来并行化 for 循环。但似乎使用 openMP 比不使用它需要更长的时间。这是我的代码:

#include <omp.h>
#include <stdio.h>
#include <ctime>
#include <ratio>
#include <chrono>
using namespace std::chrono;

void simple(int n)
{
int i;
int d;
#pragma omp parallel
#pragma omp for
for (i=1; i<n; i++) /* i is private by default */
    d = (10000 + 4564) / 2.0;
}


int main ()
{
high_resolution_clock::time_point t1 = high_resolution_clock::now();
simple(90000000);
high_resolution_clock::time_point t2 = high_resolution_clock::now();
duration<double> time_span = duration_cast<duration<double>>(t2 - t1);
std::cout << "Time: " << time_span.count() << " seconds.";
}

我使用这个命令行来编译它:

g++ -g -O2  test-2.cpp  -o l  -std=gnu++11

没有 OpenMP 所需的时间:1.885e-06

并使用 OpenMP:0.00434578

问题 1:为什么在上面的代码中使用 OpenMP 的时间比没有使用 OpenMP 的时间长?我的错误是什么?

问题 2:如何在上述 for 循环中使用 OpenMP,使其计算时间比不使用 OpenMP 更快?

标签: c++openmp

解决方案


推荐阅读