clock_gettimeを呼び出して、LinuxですべてのスレッドのCPU時間を取得できますか?

clock_gettimeを呼び出して、LinuxですべてのスレッドのCPU時間を取得できますか?

システムで実行されているスレッドのTIDがわかっている場合は、そのスレッドのpthread CPUクロックIDを簡単に計算できます。しかし、clock_gettime私のプログラムから呼び出してCPU時間を取得できますか?私の実験ではこれは不可能であることを示しましたが、それを確認できるソースを見つけることができませんでした。

そうでない場合、特定のスレッドに対して高解像度CPU時間を取得する方法はありますか?/proc/stat情報は提供されますが、jiffiesよりも正確な情報が必要です。

ベストアンサー1

私の実験では、各スレッドのCPU時間を追跡するために生成されたクロックがプロセス固有のクロックカテゴリに属しているため、他のプロセス内で簡単にアクセスできないことがわかりました。私はこの結論を出した。

#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;
}

おすすめ記事