简体   繁体   中英

Per thread CPU statistics in Linux

I want to report the amount of CPU time used per thread in a server process (written in C/C++ on Linux). I can't find the equivalent of GetThreadTimes() on Windows, but that's what I'm looking for.

Can anyone point me in the right direction?

getrusage(2) with RUSAGE_THREAD. From the man page:

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.

The standard interface to per-process kernel statistics is the /proc filesystem. If you do " man proc " you can see what information is stored, but for per-thread resource consumption you'll want /proc/PID/task/TID/stat , where PID is the process ID and TID is the thread ID.

Here's some sample output for my current shell; you'll need to look at the manpage to decipher it:

> 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_gettime(2) with CLOCK_THREAD_CPUTIME_ID. Here's an example to get per-thread CPU time in seconds:

struct timespec ts;
if (clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts) == 0) {
   return (double)ts.tv_sec + (double)ts.tv_nsec / 1000000000;
}
return 0;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM