OpenMP
krisrak
24.9K views
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
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
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Suggested playgrounds
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;
}