如何使用C ++ / C ++ 11打印当前时间(用毫秒)(How to print current

2019-08-31 11:07发布

目前我使用此代码

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

Answer 1:

您可以使用Boost的Posix时

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

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


Answer 2:

不要浪费与提高你的时间(我知道很多人会被这句话得罪异端考虑)。

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

C ++获取毫秒的时间在Linux -时钟()似乎不正常工作

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

引用gettimeofday的可以在这里找到在opengroup.org



Answer 3:

您可以使用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。 例如:

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 ::计时 :

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();
}


Answer 4:

我建议你使用Boost.Chrono代替Boost.Datetime库,因为计时成了C ++ 11的一部分。 这里的例子



Answer 5:

这里是一个解决方案,我发现不使用升压

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


文章来源: How to print current time (with milliseconds) using C++ / C++11