Linux下C++查看程序运行时间间隔

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;

在这里插入图片描述
可以看到,虽有系统误差,但大体还是准的

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值