-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq1.cpp
93 lines (71 loc) · 2.05 KB
/
q1.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <cmath>
#include <mpi.h>
#define R_SZ 0.00001
int num_threads = 1;
inline double f(int x, int y)
{
return -std::cos(x) * std::sin(y) * std::exp(-((x - M_PI)*(x - M_PI) + (y - M_PI)*(y - M_PI)));
}
double do_work(int rank, int x_start, int x_end, int y_start, int y_end)
{
int iters = x_end - x_start;
int loop_start = (rank * (iters / num_threads));
int loop_end = loop_start + (iters / num_threads);
loop_start += x_start;
loop_end += x_start;
if (rank == num_threads-1) loop_end = x_end;
std::cout << "rank: " << rank << " start: " << loop_start << " end: " << loop_end << std::endl;
double result = 0.0;
for (int i = loop_start; i < loop_end; ++i)
{
for (int j = y_start; j < y_end; ++j)
{
result += R_SZ*R_SZ*f(x_start+i*R_SZ, y_start+j*R_SZ);
}
}
return result;
}
double myclock()
{
static time_t t_start = 0; // Save and subtract off each time
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
if( t_start == 0 ) t_start = ts.tv_sec;
return (double) (ts.tv_sec - t_start) + ts.tv_nsec * 1.0e-9;
}
int main(int argc, char** argv)
{
if (argc != 5)
{
std::cout << "usage: " << argv[0] << " [x_start] [x_end] [y_start] [y_end]" << std::endl;
return 1;
}
int x_start = std::atoi(argv[1]);
int x_end = std::atoi(argv[2]);
int y_start = std::atoi(argv[3]);
int y_end = std::atoi(argv[4]);
int rc;
int rank = 0;
double tstart, ttotal;
if ((rc = MPI_Init(&argc, &argv)) != MPI_SUCCESS)
{
std::cout << "error: cannot start mpi" << std::endl;
MPI_Abort(MPI_COMM_WORLD, rc);
}
MPI_Comm_size(MPI_COMM_WORLD,&num_threads);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
tstart = myclock();
tstart = myclock();
double result = do_work(rank, x_start, x_end, y_start, y_end);
double global_result;
MPI_Reduce(&result, &global_result, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
ttotal = myclock() - tstart;
if (rank == 0)
{
std::cout << "Result: " << global_result << std::endl;
std::cout << "Time: " << ttotal << " seconds" << std::endl;
}
MPI_Finalize();
return 0;
}