forked from funny1dog/cs442-542-f22_codes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathembarassingly_parallel.cpp
executable file
·73 lines (58 loc) · 1.59 KB
/
embarassingly_parallel.cpp
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
int main(int argc, char* argv[])
{
MPI_Init(&argc, &argv);
int rank, num_procs;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
if (argc <= 1)
{
if (rank == 0) printf("Pass global vector dimension n as command line argument\n");
return 0;
}
// Get Global Vector Sizes
int N = atoi(argv[1]);
// Split global vector indices across the processes
// Extra accounts for if num_procs does not evenly divide N
int n = N / num_procs;
int extra = N % num_procs;
int local_n = n;
int first_n = rank*n;
if (rank < extra)
{
local_n++;
first_n += rank;
}
else
{
first_n += extra;
}
// Each process gets a portion of the global vector
double* a = new double[local_n];
double* b = new double[local_n];
double* c = new double[local_n];
// Initialize lists so that process 0 holds
// a[0] = 0, a[1] = 1, ..., a[n-1] = n-1
// a[0] = n, a[1] = n+1, ..., a[n-1] = 2n-1
// ...
// So list indices stay constant, regardless of number of processes
for (int i = 0; i < local_n; i++)
{
a[i] = first_n + i;
b[i] = first_n + i;
}
// Add local lists together
for (int i = 0; i < local_n; i++)
c[i] = a[i] + b[i];
// Print local result list
for (int i = 0; i < local_n; i++)
printf("C[%d] = %e\n", first_n+i, c[i]);
// Free memory
delete[] a;
delete[] b;
delete[] c;
MPI_Finalize();
return 0;
}