vs2019 使用OpenMP--并行计算
程序员文章站
2022-07-12 20:03:13
...
要点记录
1.调试→xxxx属性,找到 “配置管理器”,选x64;
2. 调试→xxxx属性→C/C++→所有选项→OpenMP支持改为是;
3. 注意项目添加C/C++文件后出现"C/C++ ";
测试程序,判断素数
#include <omp.h>
#include <iostream>
#include <time.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
int isPrime(int lyy_num) //判断是否为素数
{
int lyy_flag = 1;
int lyy_s = sqrt(lyy_num * 1.0);
for (int j = 2;j <= lyy_s;j++)
{
if (lyy_num % j == 0)
{
lyy_flag = 0;
break;
}
}
return lyy_flag;
}
int main(int argc, int* argv[])
{
omp_set_num_threads(2);
int lyy_n, lyy_num = 0;
clock_t t1, t2;
cin >> lyy_n;
//并行
t1 = clock();
#pragma omp parallel for reduction(+:lyy_num) //reduction方法实现并行
for (int i = 2;i <= lyy_n;i++)
lyy_num += isPrime(i);
t2 = clock();
cout << lyy_num << endl;
cout << "parallel time=" << (t2 - t1) << endl;
//串行
lyy_num = 0;
t1 = clock();
for (int i = 2;i <= lyy_n;i++)
lyy_num += isPrime(i);
t2 = clock();
cout << lyy_num << endl;
cout << "serial time=" << (t2 - t1) << endl;
system("pause");
return 0;
}
vs中运行上述代码,跳出界面内输入数字,计算该数字内的素数个数。
上一篇: cuda练习(三):使用gpu进行排序
下一篇: CUDA 异步执行