关于VC中的时间函数讨论

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 laiyiling 的 blog

   关于在vc中时间函数的事业问题在论坛有不少的帖子讨论,下面结合讨论结果和相关的知识做个总结。

先从一个如何在程序中延时的问题谈起,延时的方法有
方法一: 
   使用sleep函数,它的最小单位是1ms,如延时2秒,用sleep(2000)。 
方法二: 
   使用sleep函数的不利处在于期间不能处理其他的消息,如果时间太长,就好象死机一样,所以我们利用

coledatetime类和coledatetimespan类结合windows的消息处理过程来实现延时: 
coledatetime  start_time  =  coledatetime::getcurrenttime(); 
coledatetimespan  end_time  =  coledatetime::getcurrenttime()-start_time; 
while(end_time.gettotalseconds()  <=  2) //实现延时2秒

   msg  msg; 
   getmessage(&msg,null,0,0); 
   translatemessage(&msg);
   dispatchmessage(&msg); 
   end_time  =  coledatetime::getcurrenttime-start_time; 
}//这样在延时的时候我们也能够处理其他的消息。
方法三:
    可以采用gettickcount()函数,该函数的返回值是dword型,表示以毫秒为单位的计算机启动后经历的时间间隔。
dword dwstart = gettickcount();
dword dwend = dwstart;
do

   msg  msg; 
   getmessage(&msg,null,0,0); 
   translatemessage(&msg);
   dispatchmessage(&msg);
   dwend = gettickcount(); 
} while((dwend - dwstart)  <=  2000);
上面的方法在延时的精确度上,很多时候不能满足我们的要求,下面是一种更精确的微秒级延时:
large_integer  litmp ;
longlong  qpart1,qpart2 ;
double d=0;
queryperformancecounter(&litmp) ;
// 获得初始值
qpart1 = litmp.quadpart ;
while (d<40)//你想要的时间
{
    queryperformancecounter(&litmp) ;
    qpart2 = litmp.quadpart ;
    d=(double)(qpart2 - qpart1);
}

再看看仅供win9x使用的高精度定时器:queryperformancefrequency()和queryperformancecounter(),要求计算机从硬件上支持高精度定时器。函数的原形是:
bool queryperformancefrequency(large_integer *lpfrequency);
bool queryperformancecounter (large_integer *lpcount);
数据类型largeinteger既可以是一个作为8字节长的整数,也可以是作为两个4字节长的整数的联合结构,其具体用法根据编译器是否支持64位而定。该类型的定义如下:
typeef union _ large_integer
{
    struct
    {
        dword lowpart;
        long  highpart;
    };
    longlong quadpart;
} large_integer;
在定时前应该先调用queryperformancefrequency()函数获得机器内部计时器的时钟频率。接着在需要严格计时的事件发生前和发生之后分别调用queryperformancecounter(),利用两次获得的计数之差和时钟频率,就可以计算出事件经历的精确时间。测试函数sleep(100)的精确持续时间方法:
large_integer litmp;
longlong qt1,qt2;
double dft,dff,dfm;
queryperformancefrequency(&litmp);//获得时钟频率
dff=(double)litmp.quadpart;
queryperformancecounter(&litmp);//获得初始值
qt1=litmp.quadpart;sleep(100);
queryperformancecounter(&litmp);//获得终止值
qt2=litmp.quadpart;
dfm=(double)(qt2-qt1);
dft=dfm/dff;//获得对应的时间值
需要注意的是dft计算的结果单位是秒。
参考连接:
http://dev.csdn.net/develop/article/31/31188.shtm
http://community.csdn.net/expert/faq/faq_index.asp?id=195559
http://community.csdn.net/expert/topicview1.asp?id=2663023


 

本文关键:关于VC中的时间函数讨论
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top