在Linux下面测量程序的执行时间。采用一下办法。
1 #include <sys/time.h>
2 #include <sys/resource.h>
3
4 uint64_t getusertime() {
5
6 struct rusage rusage;
7 getrusage( 0, &rusage );
8
9 // transt it to microsecond(1 s =10^6 microsecond )返回的时间是微妙级别的
10 return rusage.ru_utime.tv_sec * 1000000ULL + rusage.ru_utime.tv_usec;
11 }
首先来看 struct rusage 结构体。
1 struct rusage { 2 struct timeval ru_utime; /* user CPU time used */ 用户态下执行总时间 3 struct timeval ru_stime; /* system CPU time used */ 内核态下执行总时间。 4 long ru_maxrss; /* maximum resident set size */ 5 long ru_ixrss; /* integral shared memory size */ 6 long ru_idrss; /* integral unshared data size */ 7 long ru_isrss; /* integral unshared stack size */ 8 long ru_minflt; /* page reclaims (soft page faults) */ 9 long ru_majflt; /* page faults (hard page faults) */ 10 long ru_nswap; /* swaps */ 11 long ru_inblock; /* block input operations */ 12 long ru_oublock; /* block output operations */ 13 long ru_msgsnd; /* IPC messages sent */ 14 long ru_msgrcv; /* IPC messages received */ 15 long ru_nsignals; /* signals received */ 16 long ru_nvcsw; /* voluntary context switches */ 17 long ru_nivcsw; /* involuntary context switches */ 18 };
然后我们观察 struct rusage 中的变量 ru_utime,它是程序在用户态下执行的总时间。类型为struct timeval
1 The <sys/time.h> header defines the timeval structure that includes at least the following members: 2 3 time_t tv_sec seconds 4 suseconds_t tv_usec microseconds
我们可以在程序中采用如下的方法测量用户的执行时间。
1 int main() {
2 uint64_t start, end, totalTime;
3 start = getusertime();
4
5 /**** other parts of the program that need to measure the time*****/
6
7 end = getusertime();
8 totalTime = end - start;
9 }
函数getrusage() 使用方法为
#include <sys/time.h>
#include <sys/resource.h>
int getrusage(int who, struct rusage *usage);
Description
getrusage() returns resource usage measures for who, which can be one of the following:
RUSAGE_SELF
Return resource usage statistics for the calling process, which is the sum of resources used by all threads in the process.
RUSAGE_CHILDREN
Return 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.