/* * Generic example of master/worker program. "Tasks" just consist of * sleeping for a specified time; times to wait are generatedly * randomly from 0 to a specified maximum. * * Command-line arguments: total tasks, maximum task time, * (optional) "--verbose" for verbose output * * Sequential version using MPI timing function. */ #include #include #include #include /* a short function to print a message and exit */ void error_exit(char msg[]) { fprintf(stderr, "%s", msg); MPI_Abort(MPI_COMM_WORLD, EXIT_FAILURE); } /* function to generate a random integer in [start, end] */ int random_in_range(int start, int end) { /* use method described in "rand" man page */ return start + ((double) (end-start+1) * rand()/(RAND_MAX + 1.0)); } /* ---- main program ---- */ int main(int argc, char *argv[]) { int num_tasks; int max_task_time; double start_time, end_time; int i; int task_time; int total_task_time = 0; int verbose = 0; if (MPI_Init(&argc, &argv) != MPI_SUCCESS) { fprintf(stderr, "MPI initialization error\n"); exit(EXIT_FAILURE); } if (argc < 3) { error_exit("usage: master-worker num_tasks max_task_time (millisecs) [--verbose]\n"); } num_tasks = atoi(argv[1]); max_task_time = atoi(argv[2]); if (argc > 3) verbose = 1; start_time = MPI_Wtime(); for (i = 0; i < num_tasks; ++i) { task_time = random_in_range(1, max_task_time); total_task_time += task_time; if (verbose) printf("task time = %d\n", task_time); usleep(task_time * 1000); } end_time = MPI_Wtime(); printf("\nsequential version\n"); printf("number of tasks = %d\n", num_tasks); printf("max task time = %d\n", max_task_time); printf("total task time = %d\n", total_task_time); printf("running time = %g\n", end_time - start_time); MPI_Finalize(); return EXIT_SUCCESS; }