WINDOWS实现精确定时程序

阅读更多
一.原理及相关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 Version Header Import library Minimum operating systems Unicode
kernel32.dll
Declared in Winbase.h, includeWindows.h
Kernel32.lib
Windows 95, WindowsNT 3.1
Implemented 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;
}

你可能感兴趣的:(Windows,performance)