user304584
user304584

Reputation: 507

Does clock_t calculate the time of all threads, c++, pthreads?

Lets say my code is made of main() and in main I call 2 threads that run in parallel.

lets say that main takes 5 seconds to finish, and each thread takes 10 seconds to finish.

if I time the main program using clock_t, assuming the 2 threads run in parallel, the real time that the program will take is 15 seconds.

Now if I time it using clock_t, will that give me a time of 15 seconds or 25 seconds?

Although thread 1 and thread 2 ran in parallel, will the clock_t() calculate every cycle used by thread 1 and thread 2 and return the total number of cycles used?

I use windows mingw32, and pthreads.

example code:

main(){
 clock_t begin_time ;

  for (unsigned int id = 0; id < 2; ++id)
  {
     pthread_create(&(threads[id]), NULL, thread_func, (void *) &(data[id]));
  }


  for (unsigned int id = 0; id < 2; ++id)
  {
      pthread_join(threads[id], NULL);
  }

time = double( clock () - begin_time )/CLOCKS_PER_SEC;
}

Upvotes: 3

Views: 2115

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129364

The function clock does different things in different implementations (in particular, in different OS's). The clock function in Windows gives the number of clock-ticks from when your program started, regardless of number of threads, and regardless of whether the machine is busy or not [I believe this design decision stems from the ancient days when DOS and Windows 2.x was the fashionable things to use, and the OS didn't have a way of "not running" something].

In Linux, it gives the CPU-time used, as is the case in all Unix-like operating systems, as far as I'm aware.

Edit to clarify: My Linux system says this:

In glibc 2.17 and earlier, clock() was implemented on top of times(2). For improved precision, since glibc 2.18, it is implemented on top of clock_gettime(2) (using the CLOCK_PROCESS_CPUTIME_ID clock).

In other words, the time is for the process, not for the current thread.

To get the actual CPU-time used by your process if you are using Windows, you can (and should) use GetProcessTimes

Upvotes: 3

Related Questions