Linux下gettimeofday()函数和clock()函数:精确到毫秒级的时间
使用Linux的gettimeofday函数可以达到获取精确到毫秒级的时间,其中t1=t_start.tv_sec是公元1970年至今的时间(换算为秒),t2=t_start.tv_usec是当
前秒数下的微秒,所以将t1*1000+t2/1000可以得到当前的毫秒数。
gettimeofday()函数原型及相关数据结构:
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv , const struct timezone *tz);
struct timeval {
time_t tv_sec; /* seconds */
SUSEconds_t tv_usec; /* microseconds */
};
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
gettimeofday()函数代码举例1
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int main(int argc,char * argv[])
{
struct timeval t_start,t_end;
long cost_time = 0;
//get start time
gettimeofday(&t_start, NULL);
long start = ((long)t_start.tv_sec)*1000+(long)t_start.tv_usec/1000;
printf("Start time: %ld msn", start);
sleep(2);
usleep(5000);//5毫秒
//get end time
gettimeofday(&t_end, NULL);
long end = ((long)t_end.tv_sec)*1000+(long)t_end.tv_usec/1000;
printf("End time: %ld msn", end);
//calculate time slot
cost_time = end - start;
printf("Cost time: %ld msn", cost_time);
return 0;
}
gettimeofday()函数代码举例2
struct timeval t_start,t_end;
long cost_time = 0;
//get start time
gettimeofday(&t_start, NULL);
printf("Start time: %ld us", t_start.tv_usec);
//some operation
…
//get end time
gettimeofday(&t_end, NULL);
printf("End time: %ld us", t_end.tv_usec);
//calculate time slot
cost_time = t_end.tv_usec - t_start.tv_usec;
printf("Cost time: %ld us", cost_time);
…
输出:
Start time: 438061 us
End time: 459867 us
Cost time: 21806 us
gettimeofday()函数代码举例3:
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
int main(int argc, char * argv[]){
struct timeval tv; //(1)
while(1){
gettimeofday(&tv, NULL); //(2)
printf("time %u:%un", tv.tv_sec, tv.tv_usec);
sleep(2);
}
return 0;
}
clock()函数返回的是程序运行过程中耗掉得process time,也就是CPU time,CLOCKS_PER_SEC用来表示一秒钟会有多少个时钟计时单元,也就是硬件滴答数。通过clock()函数获取的值可实现精确到毫秒级的时间。
clock()函数代码举例:
int main(int argc, char **argv)
{
clock_t t1=clock();
ifstream in("data.txt");
vector<int> v;
for(int a;in>>a;v.push_back(a));
cout<<v.size()<<endl;
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<endl;
clock_t t2=clock();
cout<<"TotalTime:"<<t2-t1<<"ms"<<endl;
}