我希望能够报告Linux上用于服务器进程(使用C/C++编写)中每个线程所使用的CPU时间。我找不到Windows上GetThreadTimes()函数的等价物,但这正是我正在寻找的。
有没有人能指点一下我?
使用RUSAGE_THREAD的getrusage(2)。来自man页面:
int getrusage(int who, struct rusage *usage);
getrusage() returns resource usage measures for who, which can be one of the following:
[...]
RUSAGE_THREAD (since Linux 2.6.26)
Return resource usage statistics for the calling thread.
与每个进程内核统计信息的标准接口是/proc
文件系统。如果你输入 "man proc
",你可以看到存储的信息,但是对于每个线程的资源消耗, 你需要使用 /proc/PID/task/TID/stat
,其中PID
是进程ID,TID
是线程ID。
这里是我当前shell的一些示例输出;你需要查看手册才能解释它:
> more /proc/25491/task/25491/stat
25491 (bash) R 25490 25491 25491 34820 25515 4194304 955 5748 0 0 0 0 19 4 20 0
1 0 67845700 4792320 505 4294967295 134512640 135194160 3216008544 3216007164 30
86844944 0 65536 3686404 1266761467 0 0 0 17 0 0 0 0 0 0
使用CLOCK_THREAD_CPUTIME_ID的clock_gettime(2)函数。下面是一个获取每个线程CPU时间(秒)的示例:
struct timespec ts;
if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) {
return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000;
}
return 0;