I managed to get the user time and system time of the thread with an ugly hack which might not be as portable as I would like it to be, but still mostly works until I find a POSIX way to do it. Here's what I've done:
The pseudo-file /proc/
<PID>/task/
<TID>/stat file contains a lot of info about the thread
TID. Reading the file will yield 42 fields which are separated by whitespace. You can find out what each field means with "man 5 proc". utime (user time) and stime (system time) are respectively the 14th and 15th fields.
All you need to do then is parse(
*) the string you get from reading /proc/
<PID>/task/
<TID>/stat and grab the 14th field, which represents the number of
jiffies spent in user-time.
(
*) While parsing the string, keep in mind that the second field (executable name) can contain whitespaces)
The operation isn't very fast, so it shouldn't be done in a tight loop, but it's more accurate than what rusage can provide me, and the processing is mostly done in system time, so it doesn't skew the results.
Code:
unsigned long GetThreadTime()
{
char procFilename[256] ;
char buffer[1024] ;
pid_t pid = ::getpid() ;
pid_t tid = ::gettid() ;
sprintf(procFilename, "/proc/%d/task/%d/stat",pid,tid) ;
int fd, num_read ;
fd = open(procFilename, O_RDONLY, 0);
num_read = read(fd, buffer, 1023);
close(fd);
buffer[num_read] = '\0';
char* ptrUsr = strrchr(buffer, ')') + 1 ;
for(int i = 3 ; i != 14 ; ++i) ptrUsr = strchr(ptrUsr+1, ' ') ;
ptrUsr++;
long jiffies_user = atol(ptrUsr) ;
long jiffies_sys = atol(strchr(ptrUsr,' ') + 1) ;
return jiffies_user ;
}