使用C++和Boost获取当前时间(以毫秒为单位)

ghi*_*boz 51 c++ time boost timestamp milliseconds

在我的线程中(使用boost :: thread)我需要以ms或更少的时间检索当前时间并转换为ms:

实际上,在这里阅读我发现了这个:

tick = boost::posix_time::second_clock::local_time();
now  = boost::posix_time::second_clock::local_time();
Run Code Online (Sandbox Code Playgroud)

似乎工作,但我需要有一个很长的毫秒的现在...

我该怎么做?

mka*_*aes 68

您可以使用boost::posix_time::time_duration获取时间范围.就像这样

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

要获得更高的分辨率,您可以更改正在使用的时钟.例如boost::posix_time::microsec_clock,虽然这可能取决于操作系统.例如,在Windows上,boost::posix_time::microsecond_clock具有毫秒分辨率,而不是微秒.

一个稍微依赖于硬件的例子.

int main(int argc, char* argv[])
{
    boost::posix_time::ptime t1 = boost::posix_time::second_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime t2 = boost::posix_time::second_clock::local_time();
    boost::posix_time::time_duration diff = t2 - t1;
    std::cout << diff.total_milliseconds() << std::endl;

    boost::posix_time::ptime mst1 = boost::posix_time::microsec_clock::local_time();
    boost::this_thread::sleep(boost::posix_time::millisec(500));
    boost::posix_time::ptime mst2 = boost::posix_time::microsec_clock::local_time();
    boost::posix_time::time_duration msdiff = mst2 - mst1;
    std::cout << msdiff.total_milliseconds() << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在我的win7机器上.第一个输出是0或1000.第二个分辨率.第二个几乎总是500,因为时钟的分辨率更高.我希望帮助一点.

  • 谢谢,但是,例如,我需要发送现在的毫秒,我该怎么办? (3认同)
  • @ghiboz:[boost::chrono::high_resolution_clock](http://www.boost.org/doc/libs/1_47_0/doc/html/chrono/reference.html#chrono.reference.cpp0x.system_clocks_hpp.high_resolution_clock) (2认同)

Bri*_*edy 13

如果你的意思是自纪元以来的毫秒,你可以做到

ptime time_t_epoch(date(1970,1,1)); 
ptime now = microsec_clock::local_time();
time_duration diff = now - time_t_epoch;
x = diff.total_milliseconds();
Run Code Online (Sandbox Code Playgroud)

然而,你所追求的并不是特别清楚.

Boost Date Time查看DateTime文档中的示例

  • +1此外,请注意,此处的日期类型为boost :: gregorian :: date (7认同)

Mac*_*gma 8

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}
Run Code Online (Sandbox Code Playgroud)