2

Hi I am running into a little issue while working on a project for my OS class. I am instructed to use getrusage() to determine the amount of time spent in both user modes and kernel modes for a program I am writing. The issue is that it always tells me my CPU and kernel usage is zero. When looking up the function the man page mentions that if some of the members of the rusage struct are not supported by your particular version of linux they are just set to ZERO. Basically I was wondering if someone could tell me if my calling of the function and accessing its parameters is correct(so I can tell whether or not I am the issue or those features are not supported by my kernel).

Code

struct rusage usage;
struct rusage *p = &usage;

getrusage(RUSAGE_SELF, p);

printf("time in user mode = %ld\ntime in kernel mode = %ld\n", p->ru_utime.tv_sec, p->ru_stime.tv_sec);
  • Looks fine to me. How long has your process been running when you call getrusage? What does [times](http://linux.die.net/man/2/times) say? – Mikel Apr 15 '12 at 22:30
  • 2
    You should check if the return value of getrusage is -1. Then check errno to see what went wrong. – Mikel Apr 15 '12 at 22:38
  • I did that and it returns fine. I'm pretty sure at this point the at its just not setting those values because It allows me to access some of the members in the struct oh well. Would you have an alternative suggestion for getting CPU usage of a thread? –  Apr 15 '12 at 23:00
  • What Linux kernel, what distribution, and what threading library? – Mikel Apr 16 '12 at 00:18
  • 1
    If you want the usage of a single thread, you should pass `RUSAGE_THREAD` instead of `RUSAGE_SELF` as per [getrusage(2)](http://linux.die.net/man/2/getrusage). – Mikel Apr 16 '12 at 00:19

1 Answers1

5

The struct rusage members ru_utime and ru_stime are both of type struct timeval, which looks like this:

struct timeval {
    time_t      tv_sec;     /* seconds */
    suseconds_t tv_usec;    /* microseconds */
};

tv_sec tells you the number of elapsed seconds, and tv_usec tells you the number of microseconds remaining. Consequently, you'll need to print both if you want to print out the whole timeval.

Since you're only printing the tv_sec members, I suspect that your program hasn't been running long enough to have more than 0 seconds elapsed. You'll also need to print the other values:

printf("time in user mode = %ld.%06ld ", 
     p->ru_utime.tv_sec, p->ru_utime.tv_usec);
printf("time in kernel mode = %ld.%06ld\n", 
     p->ru_stime.tv_sec, p->ru_stime.tv_usec);

You can see the question I linked for other ways to print timeval structures.

Community
  • 1
  • 1
Timothy Jones
  • 21,495
  • 6
  • 60
  • 90