c++ - 时间以微秒为单位询问,但以秒为单位

标签 c++ ubuntu posix

我在 Ubuntu 下读取系统时间时遇到了一些问题。我正在尝试获取两个 ptime 变量的差异。

这是我的声明:

#include "boost/date_time/posix_time/posix_time.hpp"

boost::posix_time::ptime now  = boost::posix_time::microsec_clock::universal_time();
boost::posix_time::ptime last_time = now;
boost::posix_time::time_duration dt;
...

一段时间后我更新 now 变量并构建差异

now  = boost::posix_time::second_clock::universal_time();
dt = last_time - now;

问题是我想在我的项目中以毫秒分辨率工作,所以我将我得到的时间除以 1000(在将时间转换为微秒之后,如下所示)。

printf("%f", (double)dt.total_microseconds());

问题是我只得到了第二个分辨率的值。我已经尝试过 local_time() 而不是 universal_time()。它没有解决我的问题...

你们有什么建议吗?

谢谢你的帮助。

最佳答案

在 C++11 中可以很容易地完成这些事情。

#include <chrono>
using std::chrono::high_resolution_clock;
using std::chrono::milliseconds;
using std::chrono::nanoseconds;

auto t0 = high_resolution_clock::now();

// do something here ...

auto t1 = high_resolution_clock::now();
// get miliseconds result.
milliseconds total_milliseconds = std::chrono::duration_cast<milliseconds>(t1 - t0);
// get nanoseconds result.
nanoseconds total_nanoseconds = std::chrono::duration_cast<nanoseconds>(t1 - t0);

关于c++ - 时间以微秒为单位询问,但以秒为单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27972831/

相关文章:

memory - 带有 STL 向量的 shm_open 和 mmap

c - 消息队列 - 多个进程在 msgqueue 上发送 cmd

c++ - OpenCV : How to find the pixels inside a contour in c++

c++ - 可以仅使用 std::sort() 将零移动到数组的末尾吗?

c++ - 在 64 位机器上编译 32 位 :/usr/bin/ld: cannot find -l<someLibs>

python - 尝试使用 open() 函数失败

linux - 删除文件名开头带有数字的文件

C++ nil 与 NULL

C++11 允许对非静态和非常量成员进行类内初始化。发生了什么变化?

无法在 MacOS 上从 shm_open 写入 fd