`
deepfuture
  • 浏览: 4333430 次
  • 性别: Icon_minigender_1
  • 来自: 湛江
博客专栏
073ec2a9-85b7-3ebf-a3bb-c6361e6c6f64
SQLite源码剖析
浏览量:79428
1591c4b8-62f1-3d3e-9551-25c77465da96
WIN32汇编语言学习应用...
浏览量:68376
F5390db6-59dd-338f-ba18-4e93943ff06a
神奇的perl
浏览量:101498
Dac44363-8a80-3836-99aa-f7b7780fa6e2
lucene等搜索引擎解析...
浏览量:281206
Ec49a563-4109-3c69-9c83-8f6d068ba113
深入lucene3.5源码...
浏览量:14608
9b99bfc2-19c2-3346-9100-7f8879c731ce
VB.NET并行与分布式编...
浏览量:65559
B1db2af3-06b3-35bb-ac08-59ff2d1324b4
silverlight 5...
浏览量:31320
4a56b548-ab3d-35af-a984-e0781d142c23
算法下午茶系列
浏览量:45206
社区版块
存档分类
最新评论

WINDOWS实现精确定时程序

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

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计时器精确到微妙

    Windows计时器精确到微妙

    高精度定时程序(微秒级)源代码 highrestimer

    基于Windows 的高精度实时定时程序,精度可达到微秒级,可以用来发送串口数据等

    基于minn算法的OFDM定时同步matlab仿真【包括程序操作视频】

    这种算法在一定程度上解决了其他基于训练序列的同步算法(如S&C算法)存在的“平台效应”问题,从而实现了更精确的符号定时。 5.注意事项:注意MATLAB左侧当前文件夹路径,必须是程序所在文件夹位置,具体可以参考...

    实时控制RTX

    可实现精确定时,是并行于windows的程序系统。

    系统相关的实例50个

    定时清理Windows的指定的目录程序 定时关机程序 lzsslib 得到一个进程的状态 如是否没有反应 得到经过关联的文件类型图标 MAKEMDI2 得到当前进程的运行命令行信息 MB VIEW 存取注册表的类 NT 性能统计类 磁盘引导区...

    简易定时器1、独有三种设置提醒时间的方式,令该程序更方便易用。

    6、附带一个精确至百分之一秒的秒表(计时器),从中可查看Windows 和定时器运行了多长时间。 7、附带系统锁定功能,用户离开计算机时可以暂时锁定计算机。 8、软件连安装程序小于100KB,方便网友下载使用。 ★...

    易通文件夹锁 v4.5.8.0.zip

    定时任务提供了定时关机、重启、注销、锁定、待机、休眠、提醒、打开或关闭程序、删除文件/文件夹、备份文件/文件夹、断开网络拔号连接等操作任务。     贴心的定时多任务管理 可随意按每年、每月、每周、...

    程序天下:JavaScript实例自学手册

    20.15 执行客户端的可执行程序 20.16 自动调用OutLook发送邮件 20.17 弹出窗口选择颜色 20.18 弹出框式邮件发送 20.19 把网站作为用户的Active桌面 20.20 判断是否安装了flash插件 第21章 流行技术:DOM和userData的...

    全能自动备份工具 Perfect Backup 3.0 支持文件、应用数据、系统备份

    Perfect Backup 是适用于 Windows 的全功能定时备份软件,支持自定义文件、文件夹、应用数据以及驱动器映像备份到本地或外部驱动器、网络位置、FTP 服务器和云盘,支持电子邮件通知,软件操作简单。 可备份到任何...

    《程序天下:JavaScript实例自学手册》光盘源码

    20.15 执行客户端的可执行程序 20.16 自动调用OutLook发送邮件 20.17 弹出窗口选择颜色 20.18 弹出框式邮件发送 20.19 把网站作为用户的Active桌面 20.20 判断是否安装了flash插件 第21章 流行技术:DOM和userData的...

    基于AT89S52 单片的频率计

    定时/计数器的工作可以由编程来实现定时、计数和产生计数溢出中断要求的功 能。在构成为定时器时,每个机器周期加1 (使用12MHz 时钟时,每1us 加1),这 样以机器周期为基准可以用来测量时间间隔。在构成为计数器时,在...

    VB编程资源大全(源码 其它3)

    registry.zip 读和写注册表文件的例子(7KB) 678,xcopy.zip 模仿dos命令xcopy的功能(3KB) 679,winpaths.zip 得到计算机上windows目录和系统目录(3KB) 680,tray.zip 实现托盘程序(9KB) 681,...

    VB编程资源大全(源码 其它1)

    registry.zip 读和写注册表文件的例子(7KB) 678,xcopy.zip 模仿dos命令xcopy的功能(3KB) 679,winpaths.zip 得到计算机上windows目录和系统目录(3KB) 680,tray.zip 实现托盘程序(9KB) 681,...

    VB编程资源大全(源码 其它2)

    registry.zip 读和写注册表文件的例子(7KB) 678,xcopy.zip 模仿dos命令xcopy的功能(3KB) 679,winpaths.zip 得到计算机上windows目录和系统目录(3KB) 680,tray.zip 实现托盘程序(9KB) 681,...

    VB编程资源大全(源码 其它4)

    registry.zip 读和写注册表文件的例子(7KB) 678,xcopy.zip 模仿dos命令xcopy的功能(3KB) 679,winpaths.zip 得到计算机上windows目录和系统目录(3KB) 680,tray.zip 实现托盘程序(9KB) 681,...

    hyjl21st 5.0

    9.支持五种硬盘数据还原方式:不还原、自动还原、手动还原、定时还原和数据转储。 10.移除方式灵活。在 Windows 下移除还原精灵,会询问是否需要还原或转储数据。 11.提供还原 CMOS 功能。当 CMOS 更改后,可以选择...

    可等待定时器对象

    windows有很多内核对象,其中可等待定时器对象是一种由系统维护的,精确的定时激发的内核对象,熟练应用可等待定时器对象可以让你在自己的时间控制程序中更好地对时间事件进行控制,避免由于自己对时间控制的维护...

    Surveillant

    <br>提供命令行调用方式,方便集成到每日构建框架,或每日配置管理简报,或者简单地利用Windows任务计划定时执行。 <br>提供C#源代码,方便大家进行修改和补充完善。程序利用VSS提供的自动化编程接口IVSS对...

    德平桌面日历(calendar)7.0版

    每个人都有一些自己的秘密不想让别人知道,独特的——“私人磁盘”工具,在您的电脑上为您开辟一块私人空间,windows下访问不到,删除不了,百毒不侵,您设置的密码是您进入您的磁盘的唯一依据。即使重装机也丢失不...

    Python Cookbook

    6.20 精确和安全地使用协作的超类调用 270 第7章 持久化和数据库 273 引言 273 7.1 使用marshal模块序列化数据 275 7.2 使用pickle和cPickle模块序列化数据 277 7.3 在Pickling的时候压缩 280 7.4 对类和实例...

Global site tag (gtag.js) - Google Analytics