gpt4 book ai didi

c++ - Qt with Openmp 在 Windows 中没有提供任何加速,我使用的是 Visual Studio 2013 和 Qt 5.5

转载 作者:行者123 更新时间:2023-11-30 05:21:19 25 4
gpt4 key购买 nike

In VS 2013这是代码,当 Openmp 用于在 for 循环中引入并行性时,它不会提高速度。我想把时间缩短到 20 毫秒。是否可以?

无论是否使用 Openmp,当前执行时间约为 150 毫秒。

speedtest.pro

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt
SOURCES += main.cpp
QMAKE_CXXFLAGS += -openmp

主要.cpp

#include <iostream>
#include <chrono>
#include <ctime>
#include <omp.h>
#include <conio.h>
using namespace std;

void fun(bool *c, int *a, int aSize, int *b, int bSize)
{
#pragma omp parallel for
for (int i = 0; i<aSize; i++){
for (int j = 0; j<bSize; j++)
if ((a[i*3] - b[j*3])*(a[i*3] - b[j*3]) +
(a[i*3 + 1] - b[j*3 + 1])*(a[i*3 + 1] - b[j*3 + 1])
+ (a[i*3 + 2] - b[j*3 + 2])*(a[i*3 + 2] - b[j*3 + 2])<30)
c[i*bSize + j] = 1;
}
}


int main()
{

const int aSize = 16000;
const int bSize = 6000;

int *a = new int[aSize*3];
int *b = new int[bSize*3];
bool *c = new bool[aSize*bSize];

for (unsigned int i = 0; i < aSize; i++){
a[i*3] = (int)i;
a[i*3 + 1] = (int)i;
a[i*3 + 2] = (int)i;
}
for (unsigned int i = 0; i < bSize; i++){
b[i*3] = (int)i;
b[i*3 + 1] = (int)i;
b[i*3 + 2] = (int)i;
}

for (unsigned int i = 0; i < aSize*bSize; i++){
c[i] = 0;
}

std::chrono::time_point<std::chrono::system_clock> start, end;
start = std::chrono::system_clock::now();



fun(c, a, aSize, b, bSize);


end = std::chrono::system_clock::now();


int c1 = 0;
for (unsigned int i = 0; i < aSize*bSize; i++){
if (c[i] == 0){
c1 = 1; break;
}
}

if (c1 == 1)
cout << "Collision" << endl;
else
cout << "No collision" << endl;

std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);

std::cout << "finished computation at " << std::ctime(&end_time)
<< "elapsed time: " << 1000 * elapsed_seconds.count() << "ms\n";
getch();
delete [] a;
delete [] b;
delete [] c;


return 0;
}

最佳答案

你需要在for之前添加#pragma omp parallel for

#pragma omp parallel for
for(int i=0;i<N;++i)
{
//....
}

对于 Qt,您需要在 .pro 文件中添加:

QMAKE_CXXFLAGS += -fopenmp
QMAKE_LFLAGS += -fopenmp

关于c++ - Qt with Openmp 在 Windows 中没有提供任何加速,我使用的是 Visual Studio 2013 和 Qt 5.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40217697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com