拥有以下计时器的最简单方法

时间:2015-02-19 07:20:02

标签: c++ boost time.h

我目前正在尝试用旧的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 ++中,当我尝试使用time(0)中的< time.h >时,我只能以秒为单位获得精度,而不是浮点数。

#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

我也尝试过来自gettimeofday(struct, NULL)的{​​{1}}但是每当我使用< sys/time.h >睡觉时,它都不会算上那个时间......

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

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

boost::this_thread::sleep

部分代码我可能会提前退出while循环,我需要知道我在里面有多长时间等等。

感谢您阅读!

1 个答案:

答案 0 :(得分:0)

已知

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

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

这里有一个小片段:

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上,您通常具有15ms的精度,并且只能通过使用平台相关的时钟系统来超越此约束。

相关问题