对于以下代码,getrusage在ru_utime.tv_usec
和ru_utime.tv_sec
中返回零。
码:
#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;
}
输出:
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
Linux version 2.6.18-308
上的已编译代码在ARM板上运行可执行文件,它是
Linux version 3.8.1-2.0
最佳答案
在逻辑的两个瞬间之间计算用户使用时间,以找出消耗的时间,该时间应具有timeval的开始和结束使用时间。例如下面的示例
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
是timeval
类型的结构。如果查看其declaration,则两个成员tv_sec
和tv_usec
的类型均为long
。因此,在打印到%ld
时,请更改格式说明符。请注意,成功时getrusage()
返回0
。