c++ linux 获取毫秒_Linux下gettimeofday()函数和clock()函数:精确到毫秒级的时间

本文介绍了Linux下gettimeofday函数和clock函数用于精确计时的方法。通过示例代码展示了如何使用gettimeofday获取毫秒级时间,并计算时间差。同时,解释了clock函数返回的CPU时间及其应用场景。
摘要由CSDN通过智能技术生成

使用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

#include

#include

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()函数代码举例2struct 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

#include

#include

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 v;

for(int a;in>>a;v.push_back(a));

cout<

for(int i=0;i

cout<

cout<

clock_t t2=clock();

cout<

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值