I am trying to do some math calculations in parallel and sequential processing to see the difference.
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#include <bitset>
#include <iostream>
const int M = 100;
const int N = 100;
using namespace std;
int getRandomNum(int start, int end) {
return rand() % (end - start + 1) + start;
}
int* parallelTask(int arr[M][N]) {
int* answer = new int[M];
#pragma omp parallel
{
#pragma omp for
// here is the same code as in sequentialTask
}
}
int* sequentialTask(int arr[M][N]) {
int* answer = new int[M];
for (int i = 0; i < M; i++) {
int num = 0;
for (int j = 0; j < N; j++) {
for (int k = 1; k < N - j; k++) {
int mult = arr[i][j] * arr[i][j + k];
bitset<32> bitset = mult;
string mult_binary = bitset.to_string();
for (int l = 0; l < mult_binary.size(); l++) {
if (mult_binary[l] == '1') {
num += 1;
}
}
}
}
}
return answer;
}
void main() {
srand((unsigned int)time(NULL));
int arr[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
arr[i][j] = getRandomNum(1, 10);
}
}
double start;
double end;
start = omp_get_wtime();
parallelTask(arr);
end = omp_get_wtime();
printf("Parallel work took %f secondsn", end - start);
start = omp_get_wtime();
sequentialTask(arr);
end = omp_get_wtime();
printf("Regular work took %f secondsn", end - start);
}
The problem is that the parallel work takes more time than sequential.
Parallel work took 2,314297 seconds
Regular work took 2,011105 seconds
I added num_threads(6)
to #pragma omp parallel
and there is the result:
Parallel work took 1,742959 seconds
Regular work took 2,010864 seconds
I have a 6-core processor and I think that the difference of using parallel processing must be bigger. There is my fault?
14