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

时间:2013-04-18 07:48:02

标签: 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);
}

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

6 个答案:

答案 0 :(得分:17)

您可以使用 Boost's 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>形式,我假设它们被计算为当前日偏移量;如果它们不是,请随意使用另一个< em>起始点持续时间/时间间隔):

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';    
}

///////////////////////////////////////////////////////////////////////////////

答案 1 :(得分:16)

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

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

C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly

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

参考gettimeofday可以在opengroup.org找到

答案 2 :(得分:6)

您可以使用boost::posix_time。见SO question。例如:

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')

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

答案 3 :(得分:3)

我建议使用Boost.Chrono而不是Boost.Datetime库,因为Chrono成为了C ++ 11的一部分。 Examples here

答案 4 :(得分:1)

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

答案 5 :(得分:0)

这是我在不使用boost

的情况下找到的解决方案
1
相关问题