title: Wrong time measuring while using stopwatch, clock() and openmp
body: <p>On a ubuntu 14.04 machine I'm running a C++ code, which is parallel in some its parts (I compile with ICC, the -fopenmp option and use #pragma instructions).</p>
  
  <p>I need to measure with precision two kinds of times:</p>
  
  <p>1) a first time, let's say T1, which is the time spent by the code doing only non-parallel operations.</p>
  
  <p>2) a second time T2 which corresponds to T1 plus the time spent on further operations OPS (which can be parallelized or not).</p>
  
  <p>I measure T1 and T2 by using the following stopwatch class:</p>
  
  <pre><code>#include &lt;time.h&gt;
  #include &lt;sys/times.h&gt;
  #include &lt;iostream&gt;
  
  struct stopwatch
  {
  
      clock_t tstart;
      clock_t tprevlap;
      clock_t tlap;
      tms ustart;
      tms uprevlap;
      tms ulap;
      unsigned int clk_tk;
  
      stopwatch() :
          tstart(clock()), // clock()
          tprevlap(tstart),
          tlap(tstart),
          ustart(),
          uprevlap(),
          ulap(),
          clk_tk(sysconf(_SC_CLK_TCK))
      {
          times(&amp;ustart);
          std::copy(&amp;ustart, &amp;ustart + 1, &amp;uprevlap);
          std::copy(&amp;ustart, &amp;ustart + 1, &amp;ulap);
      };
  
      void lap()
      {
          std::copy(&amp;ulap, &amp;ulap + 1, &amp;uprevlap);
          tprevlap = tlap;
          times(&amp;ulap);
          tlap = clock();
      }
  
      double partial_wall_time()
      {
          return ((double)tlap-tstart)/CLOCKS_PER_SEC;
      }
  
      double lap_wall_time()
      {
          return ((double)(tlap-tprevlap))/CLOCKS_PER_SEC;
      }
  
      double partial_user_time()
      {
          return ((double)ulap.tms_utime-ustart.tms_utime)/clk_tk;
      }
  
      double lap_user_time()
      {
          return ((double)(ulap.tms_utime-uprevlap.tms_utime))/clk_tk;
      }
  
      double partial_sys_time()
      {
          return ((double)ulap.tms_stime-ustart.tms_stime)/clk_tk;
      }
  
      double lap_sys_time()
      {
          return ((double)ulap.tms_stime-uprevlap.tms_stime)/clk_tk;
      }
  
  };
  </code></pre>
  
  <p>If I comment the #pragma instrucions (i.e. the parallel implementation), both T1 and T2 are measured correcty while, if I implement them in a parallel way, the times reported in the log printed by using stopwatch are wrong, and much larger than the effective times.
  I'm not very interested in calculating exactly T2 (time spent while doing operations OPS is not important), but at least T1 must be measured properly.
  I suppose it's because clock() function measures the time spent in the 4 cores (threads) of my machine if the implementation is parallel. So, which other function and library should I use?</p>
  
  <p>Thank you!</p>