Parallel programming is the process of breaking down a large task into smaller sub-tasks that can be executed simultaneously, thus utilizing the available computing resources more efficiently. OpenMP is a widely used API for parallel programming in C++. It allows developers to write parallel code easily and efficiently by adding simple compiler directives to their existing code.
The OpenMP C++ application program interface lets us write applications that effectively use multiple processors. In this tutorial, we will cover how to run a parallel code in Visual C++, which supports the OpenMP 2.0 standard.
Outline
-
Configure C++ project
- Create a new C++ project
- Enable OpenMP support
-
Run code
- Add code for parallel loop and Run
Source code: https://github.com/tuttelikz/notes/tree/main/openmp-vs/OpenMPApp
Configure CPP project
Create a new cpp project
Open Visual Studio > Create a new project > Set "C++", "Windows" and "Console" filters to find the template > click Next
Enable OpenMP support
Navigate to Project > Properties
Then C/C++ > Language > Open MP Support > Choose "Yes" > Apply > OK
Importanly, make sure precompiled headers are off by Precompiled Headers > Precompiled Header > Not Using Precompiled Headers > Apply > OK
Run code
Add code to OpenMPApp.cpp
and Run
To test OpenMP functionality in C++ project, we defined a simple sum function which calculates result using conventional serial loop and parallel loop. Add the following code to OpenMPApp.cpp
#include <chrono>
#include <iostream>
#include <omp.h>
using namespace std;
// Serial for loop
int sum_serial(int n)
{
int sum = 0;
for (int i = 0; i <= n; ++i) {
sum += i;
}
cout << "Serial result: " << sum
<< endl;
return sum;
}
// Parallel for loop
int sum_parallel(int n)
{
int sum = 0;
#pragma omp parallel for reduction(+ : sum)
for (int i = 0; i <= n; ++i) {
sum += i;
}
cout << "Parallel result: " << sum
<< endl;
return sum;
}
int main()
{
int num_threads = 8;
omp_set_num_threads(num_threads);
const int n = 100000000;
auto start_time
= chrono::high_resolution_clock::now();
int result_serial = sum_serial(n);
auto end_time
= chrono::high_resolution_clock::now();
chrono::duration<double> serial_duration = end_time - start_time;
start_time = chrono::high_resolution_clock::now();
int result_parallel = sum_parallel(n);
end_time = chrono::high_resolution_clock::now();
chrono::duration<double> parallel_duration = end_time - start_time;
cout << "Serial time elapsed: "
<< serial_duration.count() << " seconds"
<< endl;
cout << "Parallel time elapsed: "
<< parallel_duration.count() << " seconds"
<< endl;
cout << "Speedup for " << num_threads << " threads: "
<< serial_duration.count()
/ parallel_duration.count()
<< endl;
return 0;
}
Press Start debugging to see the result
Thanks for reading, hope this post was useful. Stay tuned, more to come 🙂
Alternate URL: https://github.com/tuttelikz/notes/tree/main/openmp-vs
Top comments (0)