c++ - 为什么我的代码使用 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++ - Windows API 到 Arduino 串行写入工作一次,但在重写相同消息时发送损坏的数据
- vaadin - Vaadin 11: refreshAll (again)
- c# - 在 Lambda 中使用 Like 表达式
- python - 试图让一个机器人与 Selenium Python 建立不和谐的连接
- f# - 每次从 C# 调用它时,如何获取 F# fsx 脚本以重新执行和重新提取 SQL 数据?
- sugarcrm - 当另一个子面板的值改变时重新加载一个子面板
- c# - 禁用在 ComboBox 中选择下拉项目
- go - 如何检测用户是否按下键并继续
- python - python - 如何根据python中旧网址的csv检查新网址以防止重复?
- windows - 2个cpu机器更适合单任务还是多任务