栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用C ++ / C ++ 11打印当前时间(以毫秒为单位)

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用C ++ / C ++ 11打印当前时间(以毫秒为单位)

您可以使用 Boost的Posix
Time

您可以用来

boost::posix_time::microsec_clock::local_time()
从微秒分辨率的时钟获取当前时间:

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

然后,您可以计算当前日期的时间偏移量(由于持续时间的输出格式为

<hours>:<minutes>:<seconds>.<milliseconds>
,我假设它们是按当前日期偏移量计算的;如果不是,请随时为持续时间/时间间隔使用另一个
起点 ):

boost::posix_time::time_duration td = now.time_of_day();

然后你可以使用

.hours()
.minutes()
.seconds()
访问器来得到相应的值。
不幸的是,似乎没有
.milliseconds()
访问器,但是有
.total_milliseconds()
一个访问器。因此您可以做一些减法运算,以获取剩余的毫秒数,以便在字符串中进行格式化。

然后,您可以使用

sprintf()
(或者,
sprintf()_s
如果您对非便携式VC
++代码感兴趣)将这些字段格式化为原始
char
缓冲区,然后安全地将此原始C字符串缓冲区包装到健壮的便捷
std::string
实例中。

有关更多详细信息,请参见下面的注释代码。

控制台中的输出类似于:

11:43:52.276


样例代码:

///////////////////////////////////////////////////////////////////////////////#include <stdio.h>      // for sprintf()#include <iostream>     // for console output#include <string>       // for std::string#include <boost/date_time/posix_time/posix_time.hpp>//-----------------------------------------------------------------------------// Format current time (calculated as an offset in current day) in this form:////     "hh:mm:ss.SSS" (where "SSS" are milliseconds)//-----------------------------------------------------------------------------std::string now_str(){    // Get current time from the clock, using microseconds resolution    const boost::posix_time::ptime now =         boost::posix_time::microsec_clock::local_time();    // Get the time offset in current day    const boost::posix_time::time_duration td = now.time_of_day();    //    // Extract hours, minutes, seconds and milliseconds.    //    // Since there is no direct accessor ".milliseconds()",    // milliseconds are computed _by difference_ between total milliseconds    // (for which there is an accessor), and the hours/minutes/seconds    // values previously fetched.    //    const long hours        = td.hours();    const long minutes      = td.minutes();    const long seconds      = td.seconds();    const long milliseconds = td.total_milliseconds() -        ((hours * 3600 + minutes * 60 + seconds) * 1000);    //    // Format like this:    //    //      hh:mm:ss.SSS    //    // e.g. 02:15:40:321    //    //      ^          ^    //      |          |    //      123456789*12    //      ---------10-     --> 12 chars +  --> 13 chars should suffice    //      //     char buf[40];    sprintf(buf, "%02ld:%02ld:%02ld.%03ld",         hours, minutes, seconds, milliseconds);    return buf;}int main(){    std::cout << now_str() << 'n';    }///////////////////////////////////////////////////////////////////////////////


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/387314.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号