windows/ linux 下 C++ 精确到微秒的时间差

 

 

#include <sys/time.h>


int gettimeofday(struct timeval *tv, struct timezone *tz);  
功能:将目前的时间以tv所指的结构返回。  
struct timeval{  
         long tv_sec;         //秒  
         long tv_usec;        //微秒  
};
============================================================

 

#include  
#include  
#include  

bool SubTimeval(timeval &result, timeval &begin, timeval &end)
// 计算gettimeofday函数获得的end减begin的时间差,并将结果保存在result中。
{
          if ( begin.tv_sec>end.tv_sec ) return false;
    
          if ( (begin.tv_sec == end.tv_sec) && (begin.tv_usec > end.tv_usec) )   
          return   false;
    
          result.tv_sec = ( end.tv_sec - begin.tv_sec );   
          result.tv_usec = ( end.tv_usec - begin.tv_usec );   
    
          if (result.tv_usec<0) {
                   result.tv_sec--;
                   result.tv_usec+=1000000;}  

          return true;
}

int main(int argc, char **argv)  
{   
          timeval tBegin, tEnd, tDiff;
          gettimeofday(&tBegin, 0);   
          sleep(3);    // 浪费一下时间看看。:)
          gettimeofday(&tEnd, 0);   
          SubTimeval(tDiff, tBegin, tEnd);   
          printf("耗时:%d.%d 秒/n", tDiff.tv_sec, tDiff.tv_usec);  
}

 

//

static LONGLONG begin_time, end_time;

static double time_fre, time_elapsed;

static LARGE_INTEGER litmp;

 

QueryPerformanceFrequency(&litmp);
time_fre = (double)litmp.QuadPart;
QueryPerformanceCounter((LARGE_INTEGER *)&begin_time);
QueryPerformanceCounter((LARGE_INTEGER *)&end_time);
time_elapsed = (end_time - begin_time) / time_fre;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值