ctimevalgetrusagerusage

How getrusage works and What is really inside the rusage struct?


I'm trying to understand how

int getrusage(int who, struct rusage* usage)

works in order to calculate the running time of one my program.
I red the man page, 10 times maybe, and still can't get it. Tried to find something on the web, but nothing but the man page about this function is found.
What is unclear to me is what is stored inside the rusage struct - the man page isn't very clear - so I tried to run it with a debugger and directly see what's inside, but Still do not understand it, particularly how the two structs - timeval ru_utime and timeval ru_stime - work.
What's inside them assume different values, sometime 0, other times 2000 etc.

I ran a simple program with a for loop that allocates and frees memory continually. I used a stopwatch to actually see how many time it takes, it took 5.23 secs. But what I see in those structs seems to be completely unrelated:

Before loop:
ru_utime = { tv_sec = 0, tv_usec = 1000}, ru_stime = { tv_sec = 0, tv_usec = 1000}
After loop:
ru_utime = { tv_sec = 4, tv_usec = 677000}, ru_stime = { tv_sec = 0, tv_usec = 2000}

so, Can anybody explain this to me or give some good link where this is explained?
I shall be very grateful.


Solution

  • The two sub-structs you are interested in are described as follows:

    ru_utime This is the total amount of time spent executing in user mode, expressed in a timeval structure (seconds plus microseconds).

    ru_stime This is the total amount of time spent executing in kernel mode, expressed in a timeval structure (seconds plus microseconds).

    In order to prevent you from smashing all over memory, your system has two "privilege levels", called kernel mode and user mode. To keep this quick and simple, your user mode cannot see all of memory, it cannot communicate with I/O devices, and can only really do number-crunching. For anything more complicated (e.g. memory page allocation, filesystem read/write, printing things to the screen), it must ask the kernel to do it instead, which has access to all of this. This is done through a mechanism called "system calls"; have a read over this wiki article for further reading: http://en.wikipedia.org/wiki/System_call

    At a high level, the ru_utime struct returns the amount of time your program has spent doing actual computation, and the ru_stime struct returns the amount of time your program has been waiting for an answer from the kernel when doing disk access, printing to the screen etc.