7

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?

1

3 Answers 3

7

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. 
Sign up to request clarification or add additional context in comments.

6 Comments

What version of Linux is this from? I did a "man rusage" on Ubuntu 8.04 (with all development docs installed) and it didn't return anything. If it's commonly available, then it's probably a better solution than the one I posted.
Make sure you a) have the packages 'manpages-dev' and 'manpages-posix-dev' installed and b) say 'man getrusage'
Strange, I have it on Debian testing. It's from package manpages-dev version 3.22-1.
Very strange: I thought I had manpages-dev installed because I could do "man pthread_create", but apparently not. That definitely seems a better answer than mine, so +1.
OK, that sounds right, except my getrusage man page doesn't claim any knowledge of RUSAGE_THREAD. I see this is only in kernels 2.6.26 and up. I'm running RedHat ES 5.2, which from "uname -a" claims it's 2.6.18. I think that means I'm out of luck for now.
|
6

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 

1 Comment

Unfortunately, under heavy load this file fails to open 70% of the time . As a result, getrusage() from answer by @tsg is STRONGLY preferred.
2

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; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.