问题
For the following code getrusage returning zeros in ru_utime.tv_usec
and ru_utime.tv_sec
.
Code:
#include "stdlib.h"
#include "stdio.h"
#include "sys/time.h"
#include "sys/resource.h"
int getr_return, who = RUSAGE_SELF;
struct rusage usage;
main()
{
getr_return = getrusage(who, &usage);
printf(" getr_return = %d\n", getr_return);
printf(" time taken in seconds = %.61f\n", usage.ru_utime.tv_sec);
printf(" time taken in seconds = %.61f\n", usage.ru_utime.tv_usec);
Some_Mips_consuming_code().
getr_return = getrusage(who, &usage);
printf(" getr_return = %d\n", getr_return);
printf(" time taken in seconds = %.61f\n", usage.ru_utime.tv_sec);
printf(" time taken in seconds = %.61f\n", usage.ru_utime.tv_usec);
exit;
}
output:
getr_return = 0
time taken in seconds = 0.0000000000000000000000000000000000000000000000000000000000000
time taken in seconds = 0.0000000000000000000000000000000000000000000000000000000000000
getr_return = 0
time taken in seconds = 0.0000000000000000000000000000000000000000000000000000000000000
time taken in seconds = 0.0000000000000000000000000000000000000000000000000000000000000
Compiled code on Linux version 2.6.18-308
Ran executable on ARM board and it's Linux version 3.8.1-2.0
回答1:
The user usage time is calculated between two instants of the logic to find out the time consumed which should have a start and end usage of timeval. Some thing like below sample,
struct timeval start, end;
getrusage(RUSAGE_SELF, &usage);
start = usage.ru_utime;
/* Code to check the usage consumed */
getrusage(RUSAGE_SELF, &usage);
end = usage.ru_utime;
ru_utime
& ru_stime
are of structures of type timeval
. If you look its declaration both members tv_sec
& tv_usec
are of type long
. So change the format specifier when printing to %ld
. Note when on success getrusage()
returns 0
.
回答2:
Time measurement is limited in precision, resolution and accuracy. Read time(7). Don't expect significant measures for computation less than e.g. half a second.
Often, CPU time measurement is done by counting jiffies or timer interrupts (related to HZ
if you have one in your kernel).
Since you call getrusage(2) at the beginning of your main
, not much computing has happened before it (basically, only pre-main
initialization in e.g. crt0.o). So you should expect it to be near zero.
You might try using clock_gettime(2) with CLOCK_REALTIME
or CLOCK_PROCESS_CPUTIME_ID
.
来源:https://stackoverflow.com/questions/22127281/getrusage-returning-zeros-in-ru-utime-tv-usec-and-ru-utime-tv-sec