如何使用 QueryPerformanceCounter? [英] How to use QueryPerformanceCounter?

查看:31
本文介绍了如何使用 QueryPerformanceCounter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近决定我的 Timer 类需要从使用毫秒更改为微秒,经过一些研究后,我认为 QueryPerformanceCounter 可能是我最安全的选择.(Boost::Posix 上的警告说它可能不适用于 Win32 API,这让我有点失望).但是,我不确定如何实现它.

I recently decided that I needed to change from using milliseconds to microseconds for my Timer class, and after some research I've decided that QueryPerformanceCounter is probably my safest bet. (The warning on Boost::Posix that it may not works on Win32 API put me off a bit). However, I'm not really sure how to implement it.

我正在做的是调用我正在使用的任何 GetTicks() esque 函数并将其分配给 Timer 的 startingTicks 变量.然后为了找到经过的时间量,我只需从 startingTicks 中减去函数的返回值,当我重置计时器时,我只需再次调用该函数并将startingTicks 分配给它.不幸的是,从我看到的代码来看,它并不像调用 QueryPerformanceCounter() 那样简单,而且我不确定我应该将什么作为参数传递.

What I'm doing is calling whatever GetTicks() esque function I'm using and assigning it to Timer's startingTicks variable. Then to find the amount of time passed I just subtract the function's return value from the startingTicks, and when I reset the timer I just call the function again and assign startingTicks to it. Unfortunately, from the code I've seen it isn't as simple as just calling QueryPerformanceCounter(), and I'm not sure what I'm supposed to pass as its argument.

推荐答案

#include <windows.h>

double PCFreq = 0.0;
__int64 CounterStart = 0;

void StartCounter()
{
    LARGE_INTEGER li;
    if(!QueryPerformanceFrequency(&li))
    cout << "QueryPerformanceFrequency failed!
";

    PCFreq = double(li.QuadPart)/1000.0;

    QueryPerformanceCounter(&li);
    CounterStart = li.QuadPart;
}
double GetCounter()
{
    LARGE_INTEGER li;
    QueryPerformanceCounter(&li);
    return double(li.QuadPart-CounterStart)/PCFreq;
}

int main()
{
    StartCounter();
    Sleep(1000);
    cout << GetCounter() <<"
";
    return 0;
}

这个程序应该输出一个接近 1000 的数字(windows sleep 不是那么准确,但应该是 999).

This program should output a number close to 1000 (windows sleep isn't that accurate, but it should be like 999).

StartCounter() 函数记录性能计数器在 CounterStart 变量中的滴答数.GetCounter() 函数返回自 StartCounter() 上次调用以来的毫秒数作为双精度值,所以如果 GetCounter() 返回 0.001 那么自从 StartCounter() 被调用以来已经过去了大约 1 微秒.

The StartCounter() function records the number of ticks the performance counter has in the CounterStart variable. The GetCounter() function returns the number of milliseconds since StartCounter() was last called as a double, so if GetCounter() returns 0.001 then it has been about 1 microsecond since StartCounter() was called.

如果您想让计时器使用秒,请更改

If you want to have the timer use seconds instead then change

PCFreq = double(li.QuadPart)/1000.0;

PCFreq = double(li.QuadPart);

或者如果你想要微秒那么使用

or if you want microseconds then use

PCFreq = double(li.QuadPart)/1000000.0;

但实际上是为了方便,因为它返回一个双精度值.

But really it's about convenience since it returns a double.

这篇关于如何使用 QueryPerformanceCounter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆