小编典典

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

linux

目前,我使用此代码

string now() {
    time_t t = time(0);
    char buffer[9] = {0};

    strftime(buffer, 9, "%H:%M:%S", localtime(&t));
    return string(buffer);
}

格式化时间。我需要加上毫秒,所以输出的格式为:16:56:12.321


阅读 1220

收藏
2020-06-07

共1个答案

小编典典

您可以使用 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 + \0 --> 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';    
}

///////////////////////////////////////////////////////////////////////////////
2020-06-07