Linux下C++查看程序运行时间间隔
使用函数:
int gettimeofday(struct timeval *tv, struct timezone *tz)
头文件:
#include<sys/time.h>
#include<unistd.h>
函数说明:会把目前的时间有tv所指的结构返回,当前地区的信息放到tz中,
struct timeval
{
long tv_sec;//秒(long int)
long tv_usec;//微秒(long int)
}
timezone 结构定义
struct timezone
{
int tz_minuteswest;//个Greenwich时间差了多少分钟
int tz_dsttime;//日光节约时间的状态
}
返回值:成功0,失败-1,错误代码存于errno
使用例子
usleep(x);//使程序沉睡x us
sleep(x);使程序沉睡x s
timeval start,end;
gettimeofday(&start,NULL);
//this_thread::sleep_for(std::chrono::milliseconds(1000));
sleep(1);//沉睡1s
gettimeofday(&end,NULL);
cout<<"TotalTime:"<< ((end.tv_usec-start.tv_usec)+(end.tv_sec-start.tv_sec)*1000000)<<"us"<<endl;
执行结果
timeval start,end;
gettimeofday(&start,NULL);
usleep(500);//沉睡500us
gettimeofday(&end,NULL);
cout<<"TotalTime:"<< ((end.tv_usec-start.tv_usec)+(end.tv_sec-start.tv_sec)*1000000)<<"us"<<endl;
可以看到,虽有系统误差,但大体还是准的