1

If I know the TID of an arbitrary thread that is running on my system, I can easily compute its pthread cpu clock ID. But would I be able to call clock_gettime from my program and get its CPU time? My experiments suggest it's not possible, but I wasn't able to find the sources to confirm this.

If not, is there a way to get hi-res CPU time for a given thread? /proc/stat gives that information but I'd like something more accurate than jiffies.

Phoenix87
  • 121
  • 5

1 Answers1

1

My experiments seem to show that the clocks created to track CPU time of each thread fall in the category of the per-process clocks and therefore are not easily accessible from within other processes. This is what I've used to get to this conclusion

#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>


int clockid(int tid) {
  return -(2 | (tid << 3));
}


int main(int argc, char ** argv) {
  int tid = (argc == 2) ? atoi(argv[1]) : gettid();

  struct timespec tp;

  if (clock_gettime(clockid(tid), &tp) == -1) {
    printf("Error getting time (error no. %d)\n", errno);
    exit(errno);
  }

  printf("Time: %ld\n", tp.tv_nsec);

  return 0;
}
Phoenix87
  • 121
  • 5
  • Where did you get code for clockid function? Will that work on any Linux kernel > 2.6? I want a monitor of own threads inside a process, (from a special monitoring thread). Till now I only found CLOCK_THREAD_CPUTIME_ID which is for calling thread, and I want for all threads of my process.. – xakepp35 Feb 02 '22 at 23:54