12

I have sequential code to parallelize via OpenMP. I have put in the corresponding pragmas and tested it. I measure the performance gain by checking the time spent in the main function.

The weird thing is the elapsed time calculated via cpu_time() and omp_get_wtime() is different. Why?

The elapsed time according to cpu_time() is similar to the sequential time.

Before computation starts:

ctime1_ = cpu_time();
#ifdef _OPENMP
ctime1 = omp_get_wtime();
#endif

After computation ends:

ctime2_ = cpu_time();
#ifdef _OPENMP
ctime2 = omp_get_wtime();
#endif

cpu_time() function definition:

double cpu_time(void)
{
  double value;
  value = (double) clock () / (double) CLOCKS_PER_SEC;
  return value;
}

Printing result:

printf("%f - %f seconds.\n", ctime2 - ctime1, ctime2_ - ctime1_);

Sample result:

7.009537 - 11.575277 seconds.
Boann
  • 48,794
  • 16
  • 117
  • 146
mert
  • 1,942
  • 2
  • 23
  • 43

3 Answers3

18

The clock function measures cpu time, the time you spend actively on the CPU, the OMP function measures the time as it has passed during execution, two completely different things.

Your process seems to be blocked in waiting somewhere.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • 8
    On Windows, `clock()` actually measures wall time. – Mysticial Jun 11 '12 at 17:00
  • 3
    @Mysticial, again, they seem to follow there own mood, instead of the standard. The standard says: *The clock function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation.* – Jens Gustedt Jun 11 '12 at 20:02
  • @JensGustedt Sounds like they follow the standard. *The implementation's best approximation* just seems to be the wall time kek – lucidbrot Mar 21 '18 at 13:46
12

What you observe is a perfectly valid result for any parallel application - the combined CPU time of all threads as returned by clock() is usually more than the wallclock time measured by omp_get_wtime() except if your application mostly sleeps or waits.

Hristo Iliev
  • 72,659
  • 12
  • 135
  • 186
6

The clock() function returns CPU time, not wall time. Instead, use gettimeofday().

chrisaycock
  • 36,470
  • 14
  • 88
  • 125