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

How to print current time (with milliseconds) using C++ / C++11

本文关键字:c++ 为单位 时间 何使用 打印      更新时间:2023-10-16

目前我使用这个代码

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

不要在Boost上浪费时间(我知道很多人会被这种说法冒犯并认为它是异端邪说)。

这个讨论包含了两个非常可行的解决方案,它们不需要你把自己奴役于非标准的第三方库。

c++在Linux上获取毫秒时间——clock()似乎不能正常工作

http://linux.die.net/man/3/clock_gettime

gettimeofday的参考可以在opengroup.org找到

这是一个解决方案,我发现没有使用boost

std::string getCurrentTimestamp()
{
using std::chrono::system_clock;
auto currentTime = std::chrono::system_clock::now();
char buffer[80];
auto transformed = currentTime.time_since_epoch().count() / 1000000;
auto millis = transformed % 1000;
std::time_t tt;
tt = system_clock::to_time_t ( currentTime );
auto timeinfo = localtime (&tt);
strftime (buffer,80,"%F %H:%M:%S",timeinfo);
sprintf(buffer, "%s:%03d",buffer,(int)millis);
return std::string(buffer);
}

可以使用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';    
}
///////////////////////////////////////////////////////////////////////////////

这是一个非常古老的问题,但对于其他访问的人来说,这是我使用现代c++提出的解决方案…

#include <chrono>
#include <ctime>
#include <sstream>
#include <iomanip>
std::string timestamp()
{
    using namespace std::chrono;
    using clock = system_clock;
    
    const auto current_time_point {clock::now()};
    const auto current_time {clock::to_time_t (current_time_point)};
    const auto current_localtime {*std::localtime (&current_time)};
    const auto current_time_since_epoch {current_time_point.time_since_epoch()};
    const auto current_milliseconds {duration_cast<milliseconds> (current_time_since_epoch).count() % 1000};
    
    std::ostringstream stream;
    stream << std::put_time (&current_localtime, "%T") << "." << std::setw (3) << std::setfill ('0') << current_milliseconds;
    return stream.str();
}

您可以使用boost::posix_time。看看这个SO问题。例:

boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();

获取当前时间:

boost::posix_time::ptime t1 = boost::posix_time::microsec_clock::local_time();
// ('tick' and 'now' are of the type of 't1')

如果可以使用c++ 11,也可以使用c++ 11的chrono。例:

int elapsed_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();

要获取当前时间(您有几个不同的时钟可用,请参阅文档):

std::chrono::time_point<std::chrono::system_clock> t2;
t2 = std::chrono::system_clock::now();
// ('start' and 'end' are of the type of 't2')

对于以毫秒为单位的时间,您可以获得午夜到当前时间之间的持续时间。使用std::chrono:

的示例
unsigned int millis_since_midnight()
{
    // current time
    std::chrono::time_point<std::chrono::system_clock> now = std::chrono::system_clock::now();
    // get midnight
    time_t tnow = std::chrono::system_clock::to_time_t(now);
    tm *date = std::localtime(&tnow);
    date->tm_hour = 0;
    date->tm_min = 0;
    date->tm_sec = 0;
    auto midnight = std::chrono::system_clock::from_time_t(std::mktime(date));
    // number of milliseconds between midnight and now, ie current time in millis
    // The same technique can be used for time since epoch
    return std::chrono::duration_cast<std::chrono::milliseconds>(now - midnight).count();
}

我建议使用Boost。Chrono代替Boost。Datetime库,因为Chrono已成为c++ 11的一部分。例子