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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
| #include "mpi.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h>
#define MSG_SIZE 4 #define PING_COUNT 64 #define SKIP_COUNT 8
char* itoa(int num,char* str,int radix) { char index[]="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; unsigned unum; int i=0,j,k;
if(radix==10&&num<0) { unum=(unsigned)-num; str[i++]='-'; } else unum=(unsigned)num;
do { str[i++]=index[unum%(unsigned)radix]; unum/=radix;
}while(unum);
str[i]='\0';
if(str[0]=='-') k=1; else k=0;
char temp; for(j=k;j<=(i-1)/2;j++) { temp=str[j]; str[j]=str[i-1+k-j]; str[i-1+k-j]=temp; }
return str;
}
void main(int argc, char* argv[]) {
int rank, size; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Comm_rank(MPI_COMM_WORLD, &rank);
double *latency, *latency_matrix; latency = malloc(sizeof(double) * size); latency_matrix = malloc(sizeof(double) * size * size); double start, end, total; char *rbuf, *sbuf; MPI_Status status;
rbuf = malloc(sizeof(char) * MSG_SIZE); memset(rbuf, 'r', MSG_SIZE); sbuf = malloc(sizeof(char) * MSG_SIZE); memset(sbuf, 's', MSG_SIZE); for (int i = 0; i < size; i ++) { if (rank == i) { for (int j = i+1; j < size; j ++) { total = 0.0; for (int k = 0; k < PING_COUNT + SKIP_COUNT; k ++) { if (k >= SKIP_COUNT) { start = MPI_Wtime(); } MPI_Send(sbuf, MSG_SIZE, MPI_CHAR, j, 0, MPI_COMM_WORLD); MPI_Recv(rbuf, MSG_SIZE, MPI_CHAR, j, 0, MPI_COMM_WORLD, &status); if (k >= SKIP_COUNT) { end = MPI_Wtime(); total += end - start; } } latency[j] = (total * 1e6) / (2.0 * PING_COUNT); } } else if (rank > i) { for (int k = 0; k < PING_COUNT + SKIP_COUNT; k++) { MPI_Recv(rbuf, MSG_SIZE, MPI_CHAR, i, 0, MPI_COMM_WORLD, &status); MPI_Send(sbuf, MSG_SIZE, MPI_CHAR, i, 0, MPI_COMM_WORLD); } } }
MPI_Gather(latency, size, MPI_DOUBLE, latency_matrix, size, MPI_DOUBLE, 0, MPI_COMM_WORLD); if (!rank) { for (int i = 0; i < size; i ++) { for (int j = 0; j < size; j ++) { printf("%lf ", *(latency_matrix + i*size + j)); } printf("\n"); } FILE *fp; char file_name[100] = "./res/latency_matrix"; char file_hostnum[5]; itoa(size, file_hostnum, 10); strcat(file_name, file_hostnum); strcat(file_name, "_measured.txt"); fp = fopen(file_name, "w"); for (int i = 0; i < size; i ++) { for (int j = 0; j < size; j ++) { fprintf(fp, "%d ", i <= j ? (int) *(latency_matrix + i*size + j) : (int) *(latency_matrix + j*size + i)); } fprintf(fp, "\n"); } fclose(fp); printf("ok\n"); }
free(latency); free(latency_matrix); free(rbuf); free(sbuf);
MPI_Finalize(); }
|