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

Simplest way to have the following timer

本文关键字:最简单 方法 计时器 拥有      更新时间:2023-10-16

我目前正在尝试用一个旧的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.h >使用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

我也尝试过< sys/time.h >中的gettimeofday(struct, NULL),但每当我用boost::this_thread::sleep睡眠程序时,它都不计算时间。。。

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

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

// Do some stuff

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

感谢您的阅读!

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() << " millisecsn";

请注意,实际时钟分辨率与操作系统绑定。例如,在windows上,您通常具有15ms的精度,并且只有使用依赖于平台的时钟系统才能超越这一限制