#include<iostream>
#include<sys/time.h>
#include<ctime>
#include<time.h>
using namespace std;
int main(){
time_t t;
time(&t);//秒级别
cout<<t<<endl;
struct timeval tv1;
struct timeval tv2;
gettimeofday(&tv1, NULL);
usleep(100);
gettimeofday(&tv2, NULL);
//double duration = tv2.tv_sec * 1000 + tv2.tv_usec / 1000 - (tv1.tv_sec * 1000 + tv1.tv_usec / 1000);
double duration = (tv2.tv_sec - tv1.tv_sec) * 1000 + (double)(tv2.tv_usec - tv1.tv_usec) / 1000;
cout << "tv1.sec:" << tv1.tv_sec << " tv1.usec:" << tv1.tv_usec << " tv2.sec:" << tv2.tv_sec << " tv2.usec:" << tv2.tv_usec << endl;
cout << " time:" << duration << endl;
}
打印结果如下:
1403846314
tv1.sec:1403846314 tv1.usec:508652 tv2.sec:1403846314 tv2.usec:508813time:0.161
其中1403846314是linux时间戳。time_t是long类型,
timeval
{
time_t tv_sec; //秒 [long int]
suseconds_t tv_usec; //微秒 [long int]
};
timeval是结构体,微秒数量级,而clock_t是毫秒级别,需要进度更高时,使用timeval。clock使用方法如下
clock_t start, finish;
double duration;
/* 测量一个事件持续的时间*/
printf( "Time to do %ld empty loops is ", i) ;
start = clock();
while( i-- );
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;