14

I run C++ program in Linux.

There are several threads pool (for computation, for io, for ... such things).

The system call clock() gives me a way to measure the CPU time spent by all the CPU cores for the process.

However, I want to measure the CPU time spent only by the threads in the computation threads pool.

How can I achieve it?

Thanks :D

Christian.K
  • 47,778
  • 10
  • 99
  • 143
syko
  • 3,477
  • 5
  • 28
  • 51
  • This is not ideal, but i think the easiest solution is to log some message with timestamps of start and stop of each thread and get you timings by postprocessing those logs. – K. Kirsz Jul 05 '17 at 05:32

1 Answers1

15

To get CPU clock ID of every thread you can use: pthread_getcpuclockid and using this CPU clock ID you can retrieve the current thread CPU time using: clock_gettime.

Following is the sample code to demonstrate the same:

struct timespec currTime;
clockid_t threadClockId;

//! Get thread clock Id
pthread_getcpuclockid(pthread_self(), &threadClockId);
//! Using thread clock Id get the clock time
clock_gettime(threadClockId, &currTime);
Hemant Gangwar
  • 2,172
  • 15
  • 27
  • It seems you can also call `clock_gettime(CLOCK_THREAD_CPUTIME_ID, &currTime)` according to [manual](https://man7.org/linux/man-pages/man2/clock_gettime.2.html) so you don't need pthread dependency. – Alexander Pivovarov Aug 22 '20 at 22:16