2

我目前正在尝试从旧的 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循环,我需要知道我在里面多久了,等等。

感谢您的阅读!

4

1 回答 1

0

gettimeofday() is known to have issues when there are discontinuous jumps in the system time.

For portable milisecond precision have a look at chrono::high_resolution_clock()

Here a little snippet:

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";

Please note the real clock resolution is bound to the operating system. For instance, on windows you usually have a 15ms precision, and you can go beyond this constraint only by using platform dependent clocking systems.

于 2015-02-19T07:30:52.813 回答