This repository has been archived by the owner on Jun 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
average-mpi-ppv2.c
98 lines (82 loc) · 2.85 KB
/
average-mpi-ppv2.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
#include <mpi.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
// printf("we are alive %d", 0);
MPI_Status s;
int size, rank, i, j;
if (argc != 2)
{
// printf("Usage: %s filename \n", argv[0]);
return 1;
}
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// printf("%d: size=%d\n", rank, size);
if (rank == 0) // Master process
{
FILE *fd;
fd = fopen(argv[1], "r");
if (fd == NULL)
{
printf("Error: cannot open file %s \n", argv[1]);
return 1;
}
int tot_count = 0;
int sum = 0;
fscanf(fd, "%d", &tot_count);
// send "tot_count/size" numbers to the other processes
// first notify the other processes that they will count=tot_count/size numbers
int count = tot_count / size;
for (int i = 1; i < size; i++)
{
// printf("Sending %d to %d\n", count, i);
MPI_Send(&count, 1, MPI_INT, i, 0xACE5, MPI_COMM_WORLD);
// send the numbers
int *numbers = (int *)malloc(count * sizeof(int));
for (int i = 0; i < count; i++)
{
fscanf(fd, "%d", &numbers[i]);
}
// fclose(fd);
MPI_Send(numbers, count, MPI_INT, i, 0xACE5, MPI_COMM_WORLD);
// printf("Sent %d to %d of %d\n", numbers[0], i, size);
}
int tmp = 0;
for (int i = count * (size - 1); i < tot_count; i++)
{
fscanf(fd, "%d", &tmp);
sum += tmp;
}
tmp = sum;
fclose(fd);
MPI_Allreduce(&tmp, &sum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
printf("%f\n", 1.0 * sum / tot_count);
}
else
{
int count;
int local_sum = 0;
int sum;
// receive the numbers from the master process and calculate the local sum
// printf("%d Receiving data . . .\n", rank);
MPI_Recv((void *)&count, 1, MPI_INT, 0, 0xACE5, MPI_COMM_WORLD, &s);
// printf("%d Receiving %d numbers from master\n", rank, count);
int *numbers = (int *)malloc(count * sizeof(int));
// int *out = (int *)malloc(count * sizeof(int));
MPI_Recv(numbers, count, MPI_INT, 0, 0xACE5, MPI_COMM_WORLD, &s);
// printf("%d Received %d numbers from master\n", rank, count);
// printf("%d first number %d\n", rank, numbers[0]);
for (int i = 0; i < count; i++)
{
local_sum += numbers[i];
// printf("%d: received %d, local sum %d; \n", rank, numbers[i], local_sum);
}
MPI_Allreduce(&local_sum, &sum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
// printf("%d: all redmuce sum %d; loc sum: %d\n", rank, sum, local_sum);
}
MPI_Finalize();
return 0;
}