WINDOWS实现精确定时程序

本文介绍Windows环境下高精度定时器的使用方法,包括QueryPerformanceFrequency和QueryPerformanceCounter两个关键API的用法,通过示例代码展示了如何实现精确的时间间隔控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.原理及相关API
WINDOWS正确定时,不同的CPU频率可以指定同一时间间隔。
使用QueryPerformanceFrequency的API,指定每秒的频率。Q ueryPerformanceFrequencyFunction查询每秒的行为频率,这个频率在整个系统运行过程中不被改变。

The QueryPerformanceFrequency function retrieves thefrequency of the high-resolution performance counter, if oneexists. The frequency cannot change while the system isrunning.

Syntax

BOOL QueryPerformanceFrequency(      
    LARGE_INTEGER *lpFrequency);

Parameters

lpFrequency
[out] Pointer to a variable that receives thecurrent performance-counter frequency, in counts per second. If theinstalled hardware does not support a high-resolution performancecounter, this parameter can be zero.

Return Value

If the installed hardware supports a high-resolution performancecounter, the return value is nonzero.

If the function fails, the return value is zero. To get extendederror information, call GetLastError. Forexample, if the installed hardware does not support ahigh-resolution performance counter, the function fails.


Function Information

Minimum DLL Versionkernel32.dll
HeaderDeclared in Winbase.h, includeWindows.h
Import libraryKernel32.lib
Minimum operating systemsWindows 95, WindowsNT 3.1
UnicodeImplemented as Unicode version.

See Also

Timers Overview, QueryPerformanceCounter

 

QueryPerformanceCounter返回当前频率值。

二.代码例子

////////////////////////////////////////////////////////////////////

 

#include "CTimer.h"

//---------------------- default constructor------------------------------
//
//-------------------------------------------------------------------------
CTimer::CTimer(): m_FPS(0),
             m_TimeElapsed(0.0f),
             m_FrameTime(0),
             m_LastTime(0),
             m_PerfCountFreq(0)
{
 //how many ticks per sec do we get

//返回系统每秒频率
 QueryPerformanceFrequency( (LARGE_INTEGER*)&m_PerfCountFreq);
// m_TimeScale 为每频率占用的秒数
 m_TimeScale = 1.0f/m_PerfCountFreq;
}

//---------------------- constructor-------------------------------------
//
// use to specify FPS
//
//-------------------------------------------------------------------------
CTimer::CTimer(float fps): m_FPS(fps),
                    m_TimeElapsed(0.0f),
                    m_LastTime(0),
                    m_PerfCountFreq(0)
{

 //how many ticks per sec do we get

//返回系统每秒频率
 QueryPerformanceFrequency( (LARGE_INTEGER*)&m_PerfCountFreq);

 m_TimeScale = 1.0f/m_PerfCountFreq;

 //calculate ticks per frame

//m_FPS为你希望系统每秒多少频率

//m_FrameTime为你设定的每频率相当于系统实际多少频率.可理解为每频率多少时间
 m_FrameTime = (LONGLONG)(m_PerfCountFreq /m_FPS);
}


//------------------------Start()-----------------------------------------
//
// call this immediately prior to game loop.Starts the timer (obviously!)
//启动定时器
//--------------------------------------------------------------------------
void CTimer::Start()
{
 //get the time
 QueryPerformanceCounter( (LARGE_INTEGER*)&m_LastTime);

 //update time to render next frame

//m_LastTime为定时开始前的时间

// m_NextTime为下次定时到了的时间.
 m_NextTime = m_LastTime + m_FrameTime;

 return;
}

//-------------------------ReadyForNextFrame()-------------------------------
//
// returns true if it is time to move on to thenext frame step. To be used if
// FPS is set.
//检测定时是否已经到了
//----------------------------------------------------------------------------
bool CTimer::ReadyForNextFrame()
{
 if (!m_FPS)
  {
   MessageBox(NULL, "No FPS set in timer", "Doh!", 0);

    returnfalse;
  }
 
  QueryPerformanceCounter( (LARGE_INTEGER*)&m_CurrentTime);

 if (m_CurrentTime >m_NextTime)
 {//定时到了

//  m_TimeElapsed为本次定时用了多少秒

//更新定时开始前的时间 m_LastTime 

  m_TimeElapsed =(m_CurrentTime - m_LastTime) * m_TimeScale;
  m_LastTime  =m_CurrentTime;

  //update time to render nextframe
  m_NextTime = m_CurrentTime +m_FrameTime;

  return true;
 }

 return false;
}

//--------------------------- TimeElapsed--------------------------------
//
// returns time elapsed since last call to thisfunction. Use in main
// when calculations are to be based on dt.
//
//-------------------------------------------------------------------------
double CTimer::TimeElapsed()
{

//得到本次定时已经用了多少秒
 QueryPerformanceCounter( (LARGE_INTEGER*)&m_CurrentTime);
 
 m_TimeElapsed = (m_CurrentTime -m_LastTime) * m_TimeScale;
 
 m_LastTime  =m_CurrentTime;

 return m_TimeElapsed;
  
}

 

 

========================================================================================

/////////////////////////////////////

///////////////////////////////////////

///////////////////////////////////////

 

#ifndef CTIMER_H
#define CTIMER_H
//-----------------------------------------------------------------------
//
//  Name: CTimer.h
//
//  Author: Mat Buckland 2002
//
// Desc: Windows timer class for the book GameAI
//  Programming with Neural Nets and GeneticAlgorithms.
//
//-----------------------------------------------------------------------

#include


class CTimer
{

private:

 LONGLONG m_CurrentTime,
          m_LastTime,
       m_NextTime,
       m_FrameTime,
       m_PerfCountFreq;

 double  m_TimeElapsed,
       m_TimeScale;

 float   m_FPS;


public:

  //ctors
 CTimer();
 CTimer(float fps);


 //whatdayaknow, this starts the timer
 void  Start();

 //determines if enough time has passed to moveonto next frame
 bool  ReadyForNextFrame();

 //only use this after a call to theabove.
 double GetTimeElapsed(){returnm_TimeElapsed;}

 double TimeElapsed();

};

 

#endif

 

三.使用举例


int WINAPI WinMain (HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR    szCmdLine,
                   int      iCmdShow)
{
    //handle to our window
  HWND      hWnd;
   
   //our window classstructure
  WNDCLASSEX    winclass;
  
    // first fill in the window class stucture
   winclass.cbSize       = sizeof(WNDCLASSEX);
   winclass.style        = CS_HREDRAW | CS_VREDRAW;
    winclass.lpfnWndProc   =WindowProc;
    winclass.cbClsExtra   = 0;
    winclass.cbWndExtra   = 0;
    winclass.hInstance    = hInstance;
    winclass.hIcon        = LoadIcon(NULL, IDI_APPLICATION);
    winclass.hCursor      = LoadCursor(NULL, IDC_ARROW);
    winclass.hbrBackground = NULL;
    winclass.lpszMenuName  = NULL;
    winclass.lpszClassName = g_szWindowClassName;
   winclass.hIconSm      = LoadIcon(NULL, IDI_APPLICATION);

   //register the windowclass
  if(!RegisterClassEx(&winclass))
  {
   MessageBox(NULL,"Registration Failed!", "Error", 0);

   //exit theapplication
   return0;
  }

   //create the window andassign its ID tohwnd   
    hWnd = CreateWindowEx(NULL,                // extended style
                           g_szWindowClassName,  // window class name
                           g_szApplicationName,  // window caption
                           WS_OVERLAPPEDWINDOW,  // window style
                           0,                   // initial x position
                           0,                   // initial y position
                           WINDOW_WIDTH,        // initial x size
                           WINDOW_HEIGHT,       // initial y size
                           NULL,                // parent window handle
                           NULL,                // window menu handle
                           hInstance,           // program instance handle
                           NULL);               // creation parameters

    //make sure the window creation has gone OK
    if(!hWnd)
    {
      MessageBox(NULL, "CreateWindowEx Failed!", "Error!", 0);
    }
        
    //make the window visible
   ShowWindow (hWnd,iCmdShow);
    UpdateWindow (hWnd);

    // Enterthe message loop
    bool bDone =false;

    //create a timer
   CTimertimer(FRAMES_PER_SECOND);

   //start the timer
   timer.Start();

    MSG msg;

   while(!bDone)
    {
     
    while(PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )
    {
    if( msg.message == WM_QUIT )
    {
     // Stop loop if it's a quit message
     bDone = true;
    }

    else
    {
     TranslateMessage( &msg );
     DispatchMessage( &msg );
    }
    }

  if(timer.ReadyForNextFrame())
  {
    //**any gameupdate code goes in here**
     
     //this will call WM_PAINT which will render our scene
   InvalidateRect(hWnd,NULL, TRUE);
   UpdateWindow(hWnd);
    }
       
    }//endwhile

    UnregisterClass( g_szWindowClassName, winclass.hInstance );

    return msg.wParam;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值