-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavg.c
104 lines (77 loc) · 2.71 KB
/
avg.c
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include <mpi.h>
#include <assert.h>
//function to generate random numbers
float *create_rand_nums(int num_elements){
float *rand_nums = (float *)malloc(sizeof(float) * num_elements);
assert(rand_nums != NULL);
int i;
//populate random numbres
for (i =0; i < num_elements; i++){
rand_nums[i] = (rand()/ (float)RAND_MAX);
}
return rand_nums;
}
//compute average of an array of numbers
float compute_avg(float *array, int num_elements){
float sum = 0.f;
for (i = 0; i < num_elements; i++){
sum += array[i];
}
return sum/num_elements;
}
int(int argc, char** argv){
if (argc != 2) {
fprintf(stderr, "Usage: avg num_elements_per_proc\n");
exit(1);
}
int num_elements_per_proc = atoi(argv[1]);
// Seed the random number generator to get different results each time
srand(time());
//initialize the communicator
MPI_Init(NULL, NULL);
//initliaze rank und size
int rank, size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Scatter the random numbers from the root process to all processes in
float *rand_nums = NULL;
//// size will be the number of elements per process times the number
// of processes
//generate random numbers using root process
if ( rank == 0 ){
rand_nums = create_rand_nums(num_elements_per_proc * size);
}
// For each process, create a buffer that will hold a subset of the entire
// array
float *sub_rand_nums = (float *)malloc(sizeof(float)* num_elements_per_proc);
assert(sub_rand_nums != NULL);
//scatter the random numbers from root process to MPI world
MPI_Scatter(rand_nums, num_elements_per_proc, MPI_FLOAT, sub_rand_nums,
num_elements_per_proc, MPI_FLOAT, 0, MPI_COMM_WORLD);
float sub_avg = compute_avg(sub_rand_nums, num_elements_per_proc);
// Gather all partial averages down to the root process
float *sub_avgs = NULL;
if (rank == 0) {
sub_avgs = (float *)malloc(sizeof(float) * world_size);
assert(sub_avgs != NULL);
}
MPI_Gather(&sub_avg, 1, MPI_FLOAT, sub_agvs, 1, MPI_FLOAT, 0, MPI_COMM_WORLD )
//since we have all partial averages on the root, we can compute average
if(rank == 0){
float avg = compute_avg(sub_avgs, size);
printf("Avg of all elements is %f\n", avg);
float orig_avg = compute_avg(rand_nums, num_elements_per_proc * size);
printf("Avg of all elements is %f\n", orig_avg);
}
//clean up
if (world_rank == 0){
free(rand_nums);
free(sub_avgs);
}
free(sub_rand_nums);
MPI_Barrier(MPI_COMM_WOLRD);
MPI_Finalize();
}