linux时间函数

#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:508813

 time: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;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值