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

Pro*_*lon 19 c++ linux windows time c++11

目前我使用此代码

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

    strftime(buffer, 9, "%H:%M:%S", localtime(&t));
    return string(buffer);
}
Run Code Online (Sandbox Code Playgroud)

格式化时间.我需要添加毫秒,因此输出的格式为:16:56:12.321

Mr.*_*C64 17

你可以使用Boost的Posix Time.

您可以使用boost::posix_time::microsec_clock::local_time()从微秒分辨率时钟获取当前时间:

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
Run Code Online (Sandbox Code Playgroud)

然后你可以计算当天的时间偏移量(因为你的持续时间输出是在表格中<hours>:<minutes>:<seconds>.<milliseconds>,我假设它们被计算为当前日偏移量;如果不是,则可以使用另一个起点来确定持续时间/时间间隔):

boost::posix_time::time_duration td = now.time_of_day();
Run Code Online (Sandbox Code Playgroud)

然后你可以使用.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';    
}

///////////////////////////////////////////////////////////////////////////////
Run Code Online (Sandbox Code Playgroud)

  • 非常好的解释代码很好的答案.精彩! (2认同)

Mar*_*off 16

不要在Boost上浪费你的时间(我知道许多人会被这句话冒犯并认为它是异端邪说).

本讨论包含两个非常可行的解决方案,不要求您将自己奴役到非标准的第三方库.

C++在Linux上获得毫秒时间 - clock()似乎无法正常工作

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

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

  • 如果你刚刚发布了这个作为提升的替代品(而不是上你的肥皂盒并且反对第三方图书馆的暴政),我会给这个投票. (7认同)
  • 您的解决方案仅适用于Linux.OP要求Windows*和*Linux ...... (5认同)
  • 如果Chrono已添加到C ++ 11,请在兼容C ++ 11的编译器中使用其实现。内置功能应优先于第三方库。我没有反对Boost的东西。但是,当内置函数可以解决问题时添加整个库将为项目/代码增加不必要的复杂性/开销。 (2认同)

小智 13

这是我在不使用 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);
}
Run Code Online (Sandbox Code Playgroud)

  • 我认为你不能假设 `time_since_epoch()` 总是返回一个周期为 1 纳秒的持续时间。就像[安东尼·尼科尔斯的回答](/sf/answers/4640406921/)一样,您需要明确地将持续时间转换为某个时间段。 (2认同)

Ant*_*lls 9

这是一个非常古老的问题,但对于其他来访的人来说,这是我使用现代 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();
}
Run Code Online (Sandbox Code Playgroud)


Syn*_*xis 6

你可以用boost::posix_time.看到这个问题.例如:

boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
Run Code Online (Sandbox Code Playgroud)

获取当前时间:

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

如果可以使用C++ 11,也可以使用C++ 11 chrono.例如:

int elapsed_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count();
Run Code Online (Sandbox Code Playgroud)

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

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

对于以毫秒为单位的时间,您可以获得午夜和当前时间之间的持续时间.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();
}
Run Code Online (Sandbox Code Playgroud)