Write a program that prints “I am even” for nodes whom rank is
divisible by two and print “I am odd” for the other odd ranking
nodes
#include <mpi.h>
#include <iostream>
int main(int argc, char* argv[]) {
// Initialize the MPI environment
MPI_Init(&argc, &argv);
// Get the rank of the process
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Check if the rank is even or odd and print the appropriate message
if (rank % 2 == 0) {
std::cout << "I am even, rank: " << rank << std::endl;
} else {
std::cout << "I am odd, rank: " << rank << std::endl;
// Finalize the MPI environment
MPI_Finalize();
return 0;
}
Code the above example program in C that calculates the sum of
numbers in parallel on different numbers of nodes. Also calculate
the execution time.
[Note: You have to use time stamp function to also print the time at
begging and end of parallel code segment]
Output: (On Single Node) Execution Time:
Output: (On Two Nodes) Execution Time: Speedup:
Output: (On Four Nodes) Execution Time: Speedup:
Output: (On Sixteen Nodes)
#include <iostream>
#include <mpi.h>
#include <ctime>
int main(int argc, char **argv) {
int mynode, totalnodes;
int sum = 0, startval, endval, accum;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &totalnodes);
MPI_Comm_rank(MPI_COMM_WORLD, &mynode);
// Start timing
double start_time = MPI_Wtime();
startval = 1000 * mynode / totalnodes + 1;
endval = 1000 * (mynode + 1) / totalnodes;
for (int i = startval; i <= endval; i++) {
sum += i;
if (mynode != 0) {
MPI_Send(&sum, 1, MPI_INT, 0, 1, MPI_COMM_WORLD);
} else {
for (int j = 1; j < totalnodes; j++) {
MPI_Recv(&accum, 1, MPI_INT, j, 1, MPI_COMM_WORLD, &status);
sum += accum;
// End timing on root node
double end_time = MPI_Wtime();
double execution_time = end_time - start_time;
std::cout << "Output: (On " << totalnodes << " Nodes)\n";
std::cout << "Execution Time: " << execution_time << " seconds\n";
std::cout << "The sum from 1 to 1000 is: " << sum << std::endl;
MPI_Finalize();
return 0;
}
Write a program in which every node receives from its left node and
sends message to its right node simultaneously
#include <iostream>
#include <mpi.h>
int main(int argc, char* argv[]) {
int rank, size;
int left, right;
int send_data, recv_data;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Calculate ranks of left and right neighbors in the ring
left = (rank - 1 + size) % size;
right = (rank + 1) % size;
// Data to be sent
send_data = rank;
// Simultaneous send and receive
MPI_Sendrecv(&send_data, 1, MPI_INT, right, 0,
&recv_data, 1, MPI_INT, left, 0,
MPI_COMM_WORLD, &status);
// Print received data
std::cout << "Process " << rank << " received data: " << recv_data << std::endl;
MPI_Finalize();
return 0;