我目前正在尝试从旧的 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)
from时,< 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)
,< sys/time.h >
但是每当我用boost::this_thread::sleep
它睡觉时,程序都不算那个时间......
我希望这里有人遇到过类似的问题并找到了解决方案。
另外,我确实需要至少毫秒精度的 dt,因为在
// Do some stuff
部分代码我可能会提前退出while循环,我需要知道我在里面多久了,等等。
感谢您的阅读!