- goal: 解決分佈式集羣上的矩陣,向量上的運算。 simulation based engineering, physics,
- 數據結構: distributed vector , distributed sparse matrix
- 基本運算: spmv, dotproduct, scaler product
- 上層algorithm: cg, pcg ..
1 #ifndef VECTOR_HPP
2 #define VECTOR_HPP
3 #include <cassert>
4 #include <cstdlib>
5
6 struct Vector_STRUCT {
7 local_int_t localLength; //!< length of local portion of the vector
8 double * values; //!< array of values
9 };
10 typedef struct Vector_STRUCT Vector;
11
12 typedef int local_int_t;
13
14 inline void InitializeVector(Vector & v, local_int_t localLength) {
15 v.localLength = localLength;
16 v.values = new double[localLength];
17 return;
18 }
33
34 inline void FillRandomVector(Vector & v) {
35 local_int_t localLength = v.localLength;
36 double * vv = v.values;
37 for (int i=0; i<localLength; ++i) vv[i] = rand() / (double)(RAND_MAX) + 1;
38 return;
39 }
58 #endif // VECTOR_HPP
//DOT_PRODUCT
1 #ifndef DOT_PRODUCT_HPP
2 #define DOT_PRODUCT_HPP
3
4 #include <mpi.h>
5 #include <cassert>
6
7 int DotProduct(const local_int_t n, const Vector & x, const Vector & y,
8 double & result) {
9 assert(x.localLength>=n); // Test vector lengths
10 assert(y.localLength>=n);
11
12 double local_result = 0.0;
13 double * xv = x.values;
14 double * yv = y.values;
15 if (yv==xv) {
16 for (local_int_t i=0; i<n; i++) local_result += xv[i]*xv[i];
17 } else {
18 for (local_int_t i=0; i<n; i++) local_result += xv[i]*yv[i];
19 }
20
21 // Use MPI's reduce function to collect all partial sums
22 double global_result = 0.0;
23 MPI_Allreduce(&local_result, &global_result, 1, MPI_DOUBLE, MPI_SUM,
24 MPI_COMM_WORLD);
25 result = global_result;
26
27 return(0);
28 }
29
30 #endif
// test main
1 #include <mpi.h>
2
3 #include <iostream>
4
5 int main(int argc, char** argv)
6 {
7 MPI_Init(&argc, &argv);
8
9 int rank, size;
10
11 MPI_Comm_rank(MPI_COMM_WORLD, &rank);
12 MPI_Comm_size(MPI_COMM_WORLD, &size);
13
14 Vector x, y;
15 int localLength = 1000;
16
17 double t1 = MPI_Wtime();
18
19 InitializeVector(x, localLength);
20 InitializeVector(y,localLength);
21 FillRandomVector(x);
22 CopyVector(x, y);
23
24 if(rank == 0) int result = 0.0;
25
26 DotProduct(localLength, x, y, result);
27
28 double t2 = MPI_Wtime();
29
30 double timing = t2 - t1;
31
32 if(rank==0) std::cout << "vector dot product = " << result << "\n"
33 << "timing = " << timing "\n"
34 << std::endl;
35
36
37 MPI_Finalize();
38
39 return 0;
40 }
test results:
1e4 0.003685 0.00370312 0.00366378 0.00367689 0.00453091
1e5 0.032934 0.0344729 0.033175 0.035444 0.035265