对于以下代码,getrusage在ru_utime.tv_usecru_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_utimeru_stimetimeval类型的结构。如果查看其declaration,则两个成员tv_sectv_usec的类型均为long。因此,在打印到%ld时,请更改格式说明符。请注意,成功时getrusage()返回0

10-04 14:18