- #include <stdio.h>
- #include <mpi.h>
- #include <string.h>
- #include <stdlib.h>
- #include <time.h>
- struct User
- {
- int id;
- int age;
- char name[25];
- char surname[30];
- float growth;
- float weight;
- };
- void randomUser(struct User* user, int id);
- int main(int argc, char *argv[])
- {
- srand(time(NULL));
- int npes;
- int myrank;
- double start, end;
- MPI_Init(&argc, &argv);
- int size, tempSize;
- MPI_Pack_size(2, MPI_INT, MPI_COMM_WORLD, &tempSize);
- size += tempSize;
- MPI_Pack_size(25, MPI_CHAR, MPI_COMM_WORLD, &tempSize);
- size += tempSize;
- MPI_Pack_size(30, MPI_CHAR, MPI_COMM_WORLD, &tempSize);
- size += tempSize;
- MPI_Pack_size(2, MPI_FLOAT, MPI_COMM_WORLD, &tempSize);
- size += tempSize;
- char *buffor = malloc(500*size);
- start = MPI_Wtime();
- MPI_Comm_size(MPI_COMM_WORLD, &npes);
- MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
- if (myrank == 0) {
- int position = 0;
- struct User users[500];
- for(int i = 0; i < 500; i++) {
- randomUser(&users[i], i);
- MPI_Pack(&users[i].id, 1, MPI_INT, buffor, 500*size, &position, MPI_COMM_WORLD);
- MPI_Pack(&users[i].age, 1, MPI_INT, buffor, 500*size, &position, MPI_COMM_WORLD);
- MPI_Pack(&users[i].name, 1, MPI_CHAR, buffor, 500*size, &position, MPI_COMM_WORLD);
- MPI_Pack(&users[i].surname, 1, MPI_CHAR, buffor, 500*size, &position, MPI_COMM_WORLD);
- MPI_Pack(&users[i].growth, 1, MPI_FLOAT, buffor, 500*size, &position, MPI_COMM_WORLD);
- MPI_Pack(&users[i].weight, 1, MPI_FLOAT, buffor, 500*size, &position, MPI_COMM_WORLD);
- }
- MPI_Send(buffor, position, MPI_PACKED, 1, 13, MPI_COMM_WORLD);
- } else if (myrank == 1) {
- MPI_Status status;
- int position = 0;
- MPI_Recv(buffor, 500*size, MPI_PACKED, 0, 13, MPI_COMM_WORLD, &status);
- struct User users[500];
- for(int i =0; i < 500; i++) {
- MPI_Unpack(buffor, 500*size, &position, &(users[i].age), 1, MPI_INT, MPI_COMM_WORLD);
- printf("ID: %d\n", users[i].age);
- }
- // printf("%s", users[1].name);
- // printf("Process 1 received user info from process 0:\nid: %d\nage: %d\nname: %s\nsurname: %s\ngrowth: %.2f\nweight: %.1f\n --------------------------- \n",
- // users[i].id, users[i].age, users[i].name, users[i].surname, users[i].growth, users[i].weight);
- }
- end = MPI_Wtime();
- MPI_Finalize();
- if (myrank == 0) {
- printf("end of process %lf\n", end-start);
- }
- return 0;
- }
- void randomUser(struct User* user, int id) {
- user->id = id;
- user->age = (rand() % 30) + 18;
- int nameLength = (rand() % 21) + 5;
- for(int i = 0; i < nameLength; i++) {
- user->name[i] = 'a' + (rand() % 26);
- }
- user->name[nameLength] = 0;
- int surnameLength = (rand() % 26) + 5;
- for(int i = 0; i < nameLength; i++) {
- user->surname[i] = 'a' + (rand() % 26);
- }
- user->surname[surnameLength] = 0;
- user->growth = (2.0 - 1.3) * (rand() / (double)RAND_MAX) + 1.3;
- user->weight = (120.0 - 40.0) * (rand() / (double)RAND_MAX) + 40.0;
- }