在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 seconds
suseconds_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);
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.