c++ linux 获取毫秒_Linux c++获取本地毫秒级精确时间

时间函数介绍

Linux c/c++中提供了很多操作时间的库函数,这里简要介绍。

使用头文件 #include

常用的时间函数包括以下:

time

原型:time_t time(time_t *t);

返回从公元1970年1月1日的UTC时间从0时0分0秒算起到现在所经过的秒数

如果t 并非空指针的话,此函数也会将返回值存到t指针所指的内存

成功则返回秒数,失败则返回((time_t)-1)值,错误原因存于errno中

localtime

原型:struct tm *localtime(const time_t * timep);

将参数timep所指的time_t结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果由结构tm返回

成功则返回0,失败返回-1,错误代码存于errno

结构tm的定义如下,此函数返回的时间日期已经转换成当地时区 struct tm {

int tm_sec;

int tm_min;

int tm_hour;

int tm_mday;

int tm_mon;

int tm_year;

int tm_wday;

int tm_yday;

int tm_isdst;

};

gettimeofday

原型:int gettimeofday ( struct timeval * tv , struct timezone * tz )

把目前的时间由tv所指的结构返回,当地时区的信息则放到tz所指的结构中

timeval结构定义为: struct timeval {

long tv_sec; /*秒*/

long tv_usec; /*微秒*/

};

timezone 结构定义为: struct timezone {

int tz_minuteswest; /*和Greenwich 时间差了多少分钟*/

int tz_dsttime; /*日光节约时间的状态*/

};

ctime

原型:char *ctime(const time_t *timep);

将参数timep所指的time_t结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形态返回

此函数已经由时区转换成当地时间,字符串格式为Wed Jun 30 21 :49 :08 1993

asctime

原型:char * asctime(const struct tm * timeptr);

将参数timeptr所指的tm结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果以字符串形态返回

此函数已经由时区转换成当地时间,字符串格式为: Wed Jun 30 21:49:08 1993\n

若再调用相关的时间日期函数,此字符串可能会被破坏。此函数与ctime不同处在于传入的参数是不同的结构

gmtime

原型:struct tm* gmtime(const time_t*timep);

将参数timep 所指的time_t 结构中的信息转换成真实世界所使用的时间日期表示方法,然后将结果由结构tm返回

settimeofday

原型:int settimeofday ( const struct timeval *tv,const struct timezone *tz);

把目前时间设成由tv所指的结构信息,当地时区信息则设成tz所指的结构

注意,只有root权限才能使用此函数修改时间

更多详细信息请使用man手册。

获取精确到毫秒的时间

可以结合time, localtime, strftime得到本地时间,精确到秒。代码如下:

static string CurrentLocalTime(void)

{

time_t t; //秒时间

tm *local; //本地时间

char buf[128] = {0};

t = time(NULL); //获取目前秒时间

local = localtime(&t); //转为本地时间,注意,该函数非线程安全,下面的例子会使用线程安全函数localtime_r

strftime(buf, 64, "%Y-%m-%d %H:%M:%S", local); //根据需要自定义格式

return buf;

}

要想得到精确到毫秒的时间,就需要使用gettimeofday了。代码如下:

/**

* @name: GetLocalTimeWithMs

* @msg: 获取本地时间,精确到毫秒

* @param {type}

* @return: string字符串,格式为YYYYMMDDHHMMSSsss,如:20190710130510368

*/

static string GetLocalTimeWithMs(void)

{

string defaultTime = "19700101000000000";

try

{

struct timeval curTime;

gettimeofday(&curTime, NULL);

int milli = curTime.tv_usec / 1000;

char buffer[80] = {0};

struct tm nowTime;

localtime_r(&curTime.tv_sec, &nowTime);//把得到的值存入临时分配的内存中,线程安全

strftime(buffer, sizeof(buffer), "%Y%m%d%H%M%S", &nowTime);

char currentTime[84] = {0};

snprintf(currentTime, sizeof(currentTime), "%s%03d", buffer, milli);

return currentTime;

}

catch(const std::exception& e)

{

return defaultTime;

}

catch (...)

{

return defaultTime;

}

}

得到字符串表示的本地时间信息后,可根据需要对字符串进行操作,简单方便。

c11获取时间戳

c11提供了chrono,专门用来处理时间相关任务。它是子命名空间,位于std下。详细内容可以参考 std::chrono。

这里介绍一下常用的两种场景:获取当前时间戳和计算时间跨度(可以用来计算某段程序的耗时)。

获取当前时间戳

// get current local time stamp

int64_t getCurrentLocalTimeStamp()

{

std::chrono::time_point<:chrono::system_clock std::chrono::milliseconds> tp = std::chrono::time_point_cast<:chrono::milliseconds>(std::chrono::system_clock::now());

auto tmp = std::chrono::duration_cast<:chrono::milliseconds>(tp.time_since_epoch());

return tmp.count();

// return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count();

}

其中,system_clock是系统级的时钟,能够获取当前的 time_point。它的 now 静态成员方法用来获取当前时间。

time_point 的 time_since_epoch 成员方法获取 1970 以来的时间。

然后通过 time_point_cast 或者 duration_cast 的 count 方法获取具体时间。

获取时间跨度

int countTimeConsume()

{

using namespace std::chrono;

high_resolution_clock::time_point t1 = high_resolution_clock::now();

std::cout << "printing out 1000 stars...\n";

for (int i = 0; i < 1000; ++i)

std::cout << "*";

std::cout << std::endl;

high_resolution_clock::time_point t2 = high_resolution_clock::now();

duration time_span = t2 - t1;

std::cout << "It took me " << time_span.count() << " milliseconds.";

std::cout << std::endl;

return 0;

}

关于 system_clock、steady_clock、high_resolution_clock 的具体说明及区别,可能参考Difference between std::system_clock and std::steady_clock。

总结

本地时间的获取在各种程序中使用率较高,可以放在项目的util中,供所有代码使用。

由于还没有理解透彻,不当之处请不吝指出哈。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值