我希望能够使用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;
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次&#34; 0&#34;直到它最终打印出一个总是非常接近&#34; 15625&#34;微秒(15.625毫秒)。
我的问题是,为什么之间没有任何东西?我想知道我的实现是否错误或者high_resolution_clock的精度是否很奇怪。有什么想法吗?
编辑:我在Windows 8计算机上使用带有mingw32编译器的Codeblocks。
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>();
}
对我而言,它打印:&#34; 1000 ns&#34;。所以我猜high_resolution_clock的精度为1微秒吧?然而在我的测试中它似乎有16毫秒的精度?
答案 0 :(得分:1)
您使用的是什么系统? (我猜它的Windows?已知Visual Studio有这个问题,现在已在VS 2015中修复,请参阅bug report)。在某些系统上,high_resolution_clock
被定义为system_clock
的别名,它可能具有非常低的分辨率,例如您看到的16毫秒。
例如,见question。
答案 1 :(得分:0)
我在Windows 10上使用msys2存在相同的问题:对于我测试的大多数子功能,返回的增量为0,突然返回15xxx或24xxx微秒。我认为我的代码中有问题,因为所有教程都没有提到任何问题。
对于difftime(finish, start)
在time.h中也是如此,通常返回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