安装
- 进入官网OpenMP,下载稳定版本。
- 解压后进入文件夹,运行
./configure --prefix=/home/jame/Public/openmp
(自定义路径) - 编译运行
make -j4
sudo make install
- 路径配置
sudo vim ~/.bashrc
添加
export PATH="$PATH:/home/jame/Public/openmp/bin"
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/home/jame/Public/openmp/lib"
- 案例测试
进入/home/jame/Downloads/openmpi-4.1.5/examples
运行(使用四个线程运行)
mpirun -np 4 hello_c
指令教程
直接参考指令教程。
个人测试代码:文章来源:https://www.toymoban.com/news/detail-788722.html
#include<omp.h>
#include<iostream>
#include <math.h>
#include <unistd.h>
using namespace std;
long long get_microseconds(void){
// 微秒单位
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return now.tv_sec * 1000000 + now.tv_nsec / 1000;
}
int main()
{
omp_set_num_threads(5);
// ********************************* section test *******************************
#pragma omp parallel sections
{
#pragma omp section
{
for(int i=0;i<2;i++){
double temp = sin(i*0.01) * cos(i*0.01);
cout << "1 " << omp_get_thread_num() << endl;
usleep(1000000);
}
}
#pragma omp section
{
for(int i=0;i<2;i++){
double temp = sin(i*0.01) * cos(i*0.01);
cout << "2 " <<omp_get_thread_num() << endl;
usleep(1000000);
}
}
}
// ********************************* static test *******************************
auto start_time = get_microseconds();
#pragma omp parallel for schedule(static)
for(int i=0;i<8;i++){
for(int i=0;i<250*250;i++){
double temp = sin(i*0.01) * cos(i*0.01);
}
cout << omp_get_thread_num() << endl;
}
auto end_time = get_microseconds();
cout << "time: "<< (- start_time + end_time) * 0.000001 << endl;
}
CMakeLists关键配置:文章来源地址https://www.toymoban.com/news/detail-788722.html
set(CMAKE_CXX_FLAGS "-Wall -fopenmp")
find_package(OpenMP REQUIRED)
if(OpenMP_FOUND)
message(STATUS "########## Found openmp ##########")
set(CMAKE_C_FLAGS ${CMAKE_C_FLAGS} ${OPENMP_C_FLAGS})
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} ${OPENMP_CXX_FLAGS})
else()
message(FATAL_ERROR "Openmp not found!")
endif()
到了这里,关于Ubuntu安装OpenMP及案例的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!