OpenMP
krisrak
31.5K views
Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
Hello OpenMP
The sections below shows how to write a simple OpenMP program.
Include Header File
OpenMP program will have to include the omp.h
header file
#include <omp.h>
OpenMP Offload
#pragma omp target map(from:is_cpu) map(tofrom:data[0:N])
Loop Parallelism
#pragma omp parallel for
Hands-on Demo
The OpenMP example shown on the right will allocate memory for an array which is initialized to some values, next the task of doubling the array values is offloaded to a device and then finally the result is printed out on the host.
Input array is inialized to:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Expected output after computation on device:
0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30
hello.cpp
Compiling OpenMP code
To compile a OpenMP program, initialize environment variables and then use icpx
to compile as shown below:
source /opt/intel/inteloneapi/setvars.sh
icpx -fiopenmp -fopenmp-targets=spir64 hello.cpp
Check OpenMP Compiler Version
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <omp.h>
#include <iostream>
static const int N = 16;
int main(){
int is_cpu = true;
int *data = static_cast<int*>(malloc(N * sizeof(int)));
for(int i=0; i<N; i++) data[i] = i;
#pragma omp target map(from:is_cpu) map(tofrom:data[0:N])
{
is_cpu=omp_is_initial_device();
#pragma omp parallel for
for (int i=0; i<N; i++)
data[i] *= 2;
}
printf ("Running on %s\n", (is_cpu?"CPU":"GPU"));
for(int i=0; i<N; i++) std::cout << data[i] << std::endl;
free(data);
return 0;
}
Enter to Rename, Shift+Enter to Preview