centos$ man 2 gettimeofday
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
struct timeval {
time_t tv_sec; // seconds
suseconds_t tv_usec; //microseconds
};
// it gives the number of seconds and microseconds since the Epoch (see time(2))
struct timezone {
int tz_minuteswest; //minutes west of Greenwich
int tz_dsttime; //type of DST correction
};
// if tv or tz is NULL, the corresponding structure is no set or returned.
简单测试用例
程序中添加两个struct timeval 来记录开始和完成的时间就可以了。
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
int main()
{
struct timeval beginTime, endTime;
if (gettimeofday(&beginTime, NULL) == -1)
return -1;
for (int i = 1; i <= 10000; i++)
for (int j = 1; j <= 10000; j++)
;
if (gettimeofday(&endTime, NULL) == -1)
return -1;
double seconds;
seconds = 1000000*(endTime.tv_sec - beginTime.tv_sec) + (endTime.tv_usec - beginTime.tv_usec);
seconds /= 1000000;
printf("using time : %f\n", seconds);
return 0;
}