/* ===================================================== OpenMP example: find min in array ===================================================== */ #include #include #include #include #include struct timeval start_time, stop_time; #define MAX 100000000 int num_threads; int start[100]; double x[MAX]; double min[100]; int main(int argc, char *argv[]) { char *s; int i; double my_min; int elapsed; /* ------------------------- Generate random number ------------------------- */ for (i = 0; i < MAX; i++) x[i] = random()/(double)1147483648; s = getenv("OMP_NUM_THREADS"); if ( s == NULL ) { cout << "Environment variable OMP_NUM_THREADS was not set" << endl; exit(1); } num_threads = atoi(s); // num_threads = omp_get_num_threads(); // Does not work with OMP_NUM_THREADS cout << "Using " << num_threads << " threads..." << endl << endl; gettimeofday(&start_time, NULL); /* ******************************************************************* */ #pragma omp parallel /* -------------------------------------- Find the min. among my number The min is stored in min[s] -------------------------------------- */ { int i, id; int n, start, stop; double my_min; n = MAX/omp_get_num_threads(); // Step size id = omp_get_thread_num(); // id is one of 0, 1, 2, ..., (num_threads-1) start = id; my_min = x[start]; for (i = start+num_threads; i < MAX; i += num_threads ) { // cout << i << endl; if ( x[i] < my_min ) my_min = x[i]; } min[id] = my_min; } /* ******************************************************************* */ my_min = min[0]; for (i = 1; i < num_threads; i++) if ( min[i] < my_min ) my_min = min[i]; gettimeofday(&stop_time, NULL); elapsed = (stop_time.tv_sec*1000000 + stop_time.tv_usec) - (start_time.tv_sec*1000000 + start_time.tv_usec); cout << "min = " << my_min << endl << endl; cout << "Elapsed time = " << elapsed << " microseconds" << endl; }