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

2021-12-31 00:00:00 timer c++ clock

在 Windows 上,clock() 以毫秒为单位返回时间,但在我正在研究的这个 Linux 机器上,它会将其四舍五入到最接近的 1000,因此精度仅为秒"级别而不是毫秒级别.

On Windows, clock() returns the time in milliseconds, but on this Linux box I'm working on, it rounds it to the nearest 1000 so the precision is only to the "second" level and not to the milliseconds level.

我找到了一个使用 QTime 类的 Qt 解决方案,实例化一个对象并在其上调用 start() 然后调用 elapsed()获取经过的毫秒数.

I found a solution with Qt using the QTime class, instantiating an object and calling start() on it then calling elapsed() to get the number of milliseconds elapsed.

我有点幸运,因为我开始使用 Qt,但我想要一个不依赖第三方库的解决方案,

I got kind of lucky because I'm working with Qt to begin with, but I'd like a solution that doesn't rely on third party libraries,

没有标准的方法可以做到这一点吗?

Is there no standard way to do this?

更新

请不要推荐 Boost ..

Please don't recommend Boost ..

如果 Boost 和 Qt 可以做到,那肯定不是魔术,他们使用的一定是标准的东西!

If Boost and Qt can do it, surely it's not magic, there must be something standard that they're using!

推荐答案

您可以在方法的开头和结尾使用 gettimeofday,然后区分这两个返回结构.您将获得如下结构:

You could use gettimeofday at the start and end of your method and then difference the two return structs. You'll get a structure like the following:

struct timeval {
  time_t tv_sec;
  suseconds_t tv_usec;
}

正如下面的两条评论所暗示的那样,clock_gettime(CLOCK_MONOTONIC) 是一个更好的选择,如果你有它,现在应该几乎无处不在.

As the two comments below suggest, clock_gettime(CLOCK_MONOTONIC) is a much better choice if you have it available, which should be almost everywhere these days.

其他人评论说您也可以将现代 C++ 与 std::chrono::high_resolution_clock 一起使用,但这并不能保证是单调的.改用steady_clock.

Someone else commented that you can also use modern C++ with std::chrono::high_resolution_clock, but that isn't guaranteed to be monotonic. Use steady_clock instead.

相关文章