cs205-lecture-examples

Example codes used during Harvard CS205 lectures
git clone https://git.0xfab.ch/cs205-lecture-examples.git
Log | Files | Refs | README | LICENSE

omp_wtime.cpp (965B)


      1 #include <iostream>
      2 #include <omp.h>
      3 #include <random>
      4 #include <unistd.h>
      5 
      6 int main(void)
      7 {
      8 #pragma omp parallel
      9     {
     10 #pragma omp single
     11         {
     12             const double resolution = omp_get_wtick();
     13             std::cout << "Clock resolution: " << std::scientific << resolution
     14                       << " sec\n";
     15         }
     16 
     17         const int tid = omp_get_thread_num();
     18         // the random number generator must be thread private -> race condition
     19         // otherwise!
     20         std::mt19937 gen(tid);
     21         std::uniform_int_distribution uniform(1, 500);
     22 
     23         const int mytime = uniform(gen) * 1000; // micro seconds
     24         const double t0 = omp_get_wtime();
     25         usleep(mytime);
     26         const double dt = omp_get_wtime() - t0;
     27 
     28 #pragma omp critical
     29         {
     30             std::cout << "Thread " << tid << ":\t" << std::scientific << dt
     31                       << " sec elapsed [expected: " << mytime * 1.0e-6 << "]\n";
     32         }
     33     }
     34     return 0;
     35 }