Linux下测量程序运行时间

来源:互联网 发布:打印机网络连接设置 编辑:程序博客网 时间:2024/05/02 03:05

在Linux下面测量程序的执行时间。采用一下办法。

#include <sys/time.h>#include <sys/resource.h>uint64_t getusertime() {struct rusage rusage;getrusage( 0, &rusage );// transt it to microsecond(1 s =10^6 microsecond )返回的时间是微妙级别的return rusage.ru_utime.tv_sec * 1000000ULL + rusage.ru_utime.tv_usec;}


首先来看 struct rusage 结构体。

struct rusage {    struct timeval ru_utime; /* user CPU time used */ 用户态下执行总时间    struct timeval ru_stime; /* system CPU time used */  内核态下执行总时间。    long   ru_maxrss;        /* maximum resident set size */    long   ru_ixrss;         /* integral shared memory size */    long   ru_idrss;         /* integral unshared data size */    long   ru_isrss;         /* integral unshared stack size */    long   ru_minflt;        /* page reclaims (soft page faults) */    long   ru_majflt;        /* page faults (hard page faults) */    long   ru_nswap;         /* swaps */    long   ru_inblock;       /* block input operations */    long   ru_oublock;       /* block output operations */    long   ru_msgsnd;        /* IPC messages sent */    long   ru_msgrcv;        /* IPC messages received */    long   ru_nsignals;      /* signals received */    long   ru_nvcsw;         /* voluntary context switches */    long   ru_nivcsw;        /* involuntary context switches */};



然后我们观察 struct rusage 中的变量 ru_utime,它是程序在用户态下执行的总时间。类型为struct timeval


The <sys/time.h> header defines the timeval structure that includes at least the following members:time_t         tv_sec      secondssuseconds_t    tv_usec     microseconds


我们可以在程序中采用如下的方法测量用户的执行时间。


int main() {    uint64_t start, end, totalTime;    start = getusertime();   /**** other parts of the program that need to measure the time*****/    end  = getusertime();    totalTime = end - start;}

函数getrusage()使用方法


#include <sys/time.h>#include <sys/resource.h>int getrusage(int who, struct rusage *usage);Descriptiongetrusage() returns resource usage measures for who, which can be one of the following:RUSAGE_SELFReturn resource usage statistics for the calling process, which is the sum of resources used by all threads in the process.
RUSAGE_CHILDRENReturn resource usage statistics for all children of the calling process that have terminated and been waited for. These statistics will include the resources used by grandchildren, and further removed descendants, if all of the intervening descendants waited on their terminated children.
RUSAGE_THREAD (since Linux 2.6.26)Return resource usage statistics for the calling thread.
                                             
0 0
原创粉丝点击