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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16077299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:44:23  来源:igfitidea点击:

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

c++linuxwindowstimec++11

提问by Prospolon

Currently I use this code

目前我使用这个代码

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

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

to format time. I need to add milliseconds, so the output has the format: 16:56:12.321

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

采纳答案by Mr.C64

You can use Boost's Posix Time.

您可以使用Boost 的 Posix Time

You can use boost::posix_time::microsec_clock::local_time()to get current time from microseconds-resolution clock:

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

boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();

Then you can compute time offset in current day (since your duration output is in the form <hours>:<minutes>:<seconds>.<milliseconds>, I'm assuming they are calculated as current day offset; if they are not, feel free to use another starting pointfor duration/time interval):

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

boost::posix_time::time_duration td = now.time_of_day();

Then you can use .hours(), .minutes(), .seconds()accessors to get the corresponding values.
Unfortunately, there doesn't seem to be a .milliseconds()accessor, but there is a .total_milliseconds()one; so you can do a little subtraction math to get the remaining milliseconds to be formatted in the string.

然后你可以使用.hours(), .minutes(),.seconds()访问器来获取相应的值。
不幸的是,似乎没有.milliseconds()访问器,但有.total_milliseconds()一个;所以你可以做一些减法运算来获得剩余的毫秒数以在字符串中格式化。

Then you can use sprintf()(or sprintf()_sif you are interested in non-portable VC++-only code) to format those fields into a raw charbuffer, and safely wrap this raw C string buffer into a robust convenient std::stringinstance.

然后您可以使用sprintf()(或者sprintf()_s如果您对非可移植的 VC++ 代码感兴趣)将这些字段格式化为原始char缓冲区,并安全地将此原始 C 字符串缓冲区包装到一个健壮的方便std::string实例中。

See the commented code below for further details.

有关更多详细信息,请参阅下面的注释代码。

Output in console is something like:

控制台中的输出类似于:

11:43:52.276

11:43:52.276



Sample code:

示例代码:

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

#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 + 
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
--> 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'; } ///////////////////////////////////////////////////////////////////////////////

回答by Synxis

You can use boost::posix_time. See this SO question. Ex:

您可以使用boost::posix_time. 看到这个问题。前任:

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

To get the current time:

获取当前时间:

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

You can also use the C++11 chrono, if you can use C++11. Ex:

您还可以使用C ++ 11时辰,如果你能使用C ++ 11。前任:

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

To get the current time (you have several different clocks available, see the doc):

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

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

For the time in milliseconds, you can get the duration between midnight and the current time. Example with std::chrono:

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

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

回答by Martin Goff

Don't waste your time with Boost (I know many will be offended by this statement and consider it heresy).

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

This discussion contains two very workable solutions that don't require you to enslave yourself to non-standard, 3rd party libraries.

此讨论包含两个非常可行的解决方案,它们不需要您将自己奴役于非标准的 3rd 方库。

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

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

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

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

References to gettimeofday can be found here at opengroup.org

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

回答by Andriy Tylychko

I'd recommend to use Boost.Chrono instead of Boost.Datetime library because Chrono became a part of C++11. Examples here

我建议使用 Boost.Chrono 而不是 Boost.Datetime 库,因为 Chrono 成为 C++11 的一部分。这里的例子

回答by Enrico Pintus

Here is a solution I found without using boost

这是我在不使用 boost 的情况下找到的解决方案

##代码##