【问题标题】:Simplest way to have the following timer拥有以下计时器的最简单方法
【发布时间】:2015-02-19 07:20:02
【问题描述】:

我目前正在尝试用旧的 python 代码用 C++ 重写一些软件。 在 python 版本中,我曾经有这样的计时器:

from time import time, sleep

t_start = time()
while (time()-t_start < 5) # 5 second timer
    # do some stuff
    sleep(0.001) #Don't slam the CPU

sleep(1)
print time()-t_start # would print something like 6.123145 notice the precision!

但是,在 C++ 中,当我尝试使用 &lt; time.h &gt; 中的 time(0) 时,我只能以秒为单位获得精度,而不是浮点数。

#include <time.h>
#include <iostream>

time_t t_start = time(0)
while (time(0) - t_start < 5) // again a 5 second timer.
{
    // Do some stuff 
    sleep(0.001) // long boost sleep method.
}
sleep(1);
std::cout << time(0)-t_start; // Prints 6 instead of 6.123145

我也从&lt; sys/time.h &gt; 尝试过gettimeofday(struct, NULL),但是每当我用boost::this_thread::sleep 休眠程序时,它都不算那个时间......

我希望这里有人遇到过类似的问题并找到了解决方案。

另外,我确实需要至少毫秒精度的 dt,因为在

// Do some stuff

部分代码我可能会提前跳出while循环,我需要知道我在里面多久了,等等。

感谢您的阅读!

【问题讨论】:

标签: c++ boost time.h


【解决方案1】:

gettimeofday() 已知会在系统时间出现不连续跳转时出现问题。

对于便携式毫秒精度,请查看 chrono::high_resolution_clock()

这里有一点sn-p:

chrono::high_resolution_clock::time_point ts = chrono::high_resolution_clock::now();
chrono::high_resolution_clock::time_point te = chrono::high_resolution_clock::now();
// ... do something ...
cout << "took " << chrono::duration_cast<chrono::milliseconds>(te - ts).count() << " millisecs\n";

请注意,真正的时钟分辨率与操作系统有关。例如,在 Windows 上,您通常有 15 毫秒的精度,而您只能通过使用依赖于平台的时钟系统来超越这个限制。

【讨论】:

  • 是否可以将差异存储为双精度??
  • 需要提到 Windows 的 boost::chrono(我相信 MSVS2015 CTP 可能会修复分辨率?)。
  • @ch0l1n3 c::duration_cast&lt;c::milliseconds&gt;(duration).count()/1000.0 例如(c=std::chrono)
  • 这样吗? double dt = chrono::duration_cast<:milliseconds>(te - ts).count()/1000.0 另外,我使用的是 linux,所以分辨率问题可能不同!
  • 我的理解是chrono::high_resolution_clock不保证“稳”不“跳”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-17
  • 1970-01-01
  • 2014-01-23
  • 2012-02-21
相关资源
最近更新 更多