/* * Generic example of master/worker program. "Tasks" just consist of * sleeping for a specified time; times to wait are generatedly * randomly from 1 to a specified maximum. * * Command-line arguments: total tasks, maximum task time, * (optional) "--verbose" for verbose output * * Sequential version using OpenMP timing function. */ /* ugly nonportable hack to make millisleep() function compile with c99 */ #define _POSIX_C_SOURCE 199309L #include #include #include #include #include /* a short function to print a message and exit */ void error_exit(char msg[]) { fprintf(stderr, "%s", msg); exit(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)); } /* function to sleep N millisecs -- not very portable */ void millisleep(int milliseconds) { struct timespec sleep_time = { 0, (long) milliseconds * 1000000 }; nanosleep(&sleep_time, NULL); } /* ---- 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; char* usage_msg = "parameters: num_tasks max_task_time [--verbose]\n"; int required_parms = 3; if (argc < required_parms) { error_exit(usage_msg); } num_tasks = atoi(argv[1]); max_task_time = atoi(argv[2]); if ((num_tasks <= 0) || (max_task_time <= 0)) { error_exit(usage_msg); } if (argc > required_parms) { if (strcmp(argv[required_parms], "--verbose") == 0) verbose = 1; else error_exit(usage_msg); } start_time = omp_get_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); millisleep(task_time); } end_time = omp_get_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); return EXIT_SUCCESS; }