我希望能够使用Clock类来测量经过的时间(对于帧时间)。 (下面的代码描述了问题。)
typedef std::chrono::high_resolution_clock::time_point timePt;
class Clock
{
timePt currentTime;
timePt lastTime;
public:
Clock();
void update();
uint64_t deltaTime();
};
#include "Clock.h"
using namespace std::chrono;
Clock::Clock()
{
currentTime = high_resolution_clock::now();
lastTime = currentTime;
}
void Clock::update()
{
lastTime = currentTime;
currentTime = high_resolution_clock::now();
}
uint64_t Clock::deltaTime()
{
microseconds delta = duration_cast<microseconds>(currentTime - lastTime);
return delta.count();
}
当我尝试这样使用Clock时
Clock clock;
while(1) {
clock.update();
uint64_t dt = clock.deltaTime();
for (int i=0; i < 10000; i++)
{
//do something to waste time between updates
int k = i*dt;
}
cout << dt << endl; //time elapsed since last update in microseconds
}
对我来说,它打印大约30倍的“ 0”,直到最终打印出一个始终非常接近“ 15625”微秒(15.625毫秒)之类的数字。
我的问题是,为什么之间没有任何关系?我想知道我的实现是错误的还是high_resolution_clock的精度表现得很奇怪。有什么想法吗?
编辑:我在Windows 8计算机上将代码块与mingw32编译器一起使用。
EDIT2:我尝试运行以下应显示high_resolution_clock精度的代码:
template <class Clock>
void display_precision()
{
typedef std::chrono::duration<double, std::nano> NS;
NS ns = typename Clock::duration(1);
std::cout << ns.count() << " ns\n";
}
int main()
{
display_precision<std::chrono::high_resolution_clock>();
}
对我来说,它打印:“ 1000 ns”。所以我猜high_resolution_clock的精度是1微秒吧?但是在我的测试中,它似乎具有16毫秒的精度?
您正在使用什么系统? (我猜是Windows?已知Visual Studio出现此问题,现在已在VS 2015中修复,请参见bug report)。在某些系统上,high_resolution_clock
仅被定义为system_clock
的别名,它可能具有非常低的分辨率,例如您看到的16 ms。例如,请参见此question。
我在Windows 10上使用msys2遇到相同的问题:对于我测试的大多数子功能,返回的增量为0,突然返回15xxx或24xxx微秒。我认为我的代码中有问题,因为所有教程都没有提到任何问题。与time.h中的difftime(finish, start)
相同,通常返回0。
我终于用high_resolution clock
更改了我所有的steady_clock
,我可以找到合适的时间:
auto t_start = std::chrono::steady_clock::now();
_cvTracker->track(image); // my function to test
std::cout << "Time taken = " << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock ::now() - t_start).count() << " microseconds" << std::endl;
// returns the proper value (or at least a plausible value)
而这大部分返回0:
auto t_start = std::chrono::high_resolution_clock::now();
_cvTracker->track(image); // my function to test
std::cout << "Time taken = " << std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - t_start).count() << " microseconds" << std::endl;
// returns 0 most of the time
difftime
似乎也不起作用:
time_t start, finish;
time(&start);
_cvTracker->track(image);
time(&finish);
std::cout << "Time taken= " << difftime(finish, start) << std::endl;
// returns 0 most of the time