Get current time in milliseconds using C++ and Boost(使用 C++ 和 Boost 获取当前时间(以毫秒为单位))
问题描述
在我的线程中(使用 boost::thread)我需要以毫秒或更短的时间检索当前时间并转换为毫秒:
In my thread (using boost::thread) I need to retrieve the current time in ms or less and to convert into ms:
实际上,在这里阅读我发现了这个:
Actually, reading here I've found this:
tick = boost::posix_time::second_clock::local_time();
now = boost::posix_time::second_clock::local_time();
而且似乎可以工作,但是在我需要一个很长的毫秒值之后……
And seems to work, but after I need to have a long value of the milliseconds of the now...
我该怎么做?
推荐答案
可以使用boost::posix_time::time_duration
获取时间范围.比如这样
You can use boost::posix_time::time_duration
to get the time range. E.g like this
boost::posix_time::time_duration diff = tick - now;
diff.total_milliseconds();
为了获得更高的分辨率,您可以更改正在使用的时钟.例如 boost::posix_time::microsec_clock
,虽然这可能取决于操作系统.例如,在 Windows 上,boost::posix_time::microsecond_clock
具有毫秒分辨率,而不是微秒.
And to get a higher resolution you can change the clock you are using. For example to the boost::posix_time::microsec_clock
, though this can be OS dependent. On Windows, for example, boost::posix_time::microsecond_clock
has milisecond resolution, not microsecond.
一个稍微依赖硬件的例子.
An example which is a little dependent on the hardware.
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;
}
在我的 win7 机器上.第一个输出是 0 或 1000.第二个分辨率.第二个几乎总是 500,因为时钟的分辨率更高.希望能帮上一点忙.
On my win7 machine. The first out is either 0 or 1000. Second resolution. The second one is nearly always 500, because of the higher resolution of the clock. I hope that help a little.
这篇关于使用 C++ 和 Boost 获取当前时间(以毫秒为单位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 C++ 和 Boost 获取当前时间(以毫秒为单位)


基础教程推荐
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01