VC函数中的延时操作

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

本文简介:选择自 pomelowu 的 blog

        说到程序中的延时,你会想到怎么做,新开一个线程?如果我的程序只用单线程,却又想让函数等上10秒才返回值,而且还不能像使用sleep函数那样不能处理其它消息呢?

        我在这里把论坛里能见到的几种延时方式总结一下。另外,主要是学习的别人的sources,版权不在我,如果本文对大家有用,请分别感谢文中的这些作者(csdn上的id):laiyiling(最熟悉的陌生人)qunkangli(雾痕)tyzyx(炸平日本岛)

        从陌生人的处理方式说起,这是延时中时间跨度最大的,单位至少在秒以上:
http://community.csdn.net/expert/faq/faq_index.asp?id=195559
见过不只一个人问起过。其实估计陌生人是直接手写的这段代码,不是从程序段中copy出来的,有一些手误,大家自己调整一下就行了
#include

coledatetime  start_time = coledatetime::getcurrenttime(); 
coledatetimespan  end_time = coledatetime::getcurrenttime() - start_time; 
while(end_time.gettotalseconds()  <=  2) 
{  
   msg  msg;  
   getmessage(&msg,null,0,0);  
   translatemessage(&msg); 
   dispatchmessage(&msg); 
   end_time = coledatetime::getcurrenttime() - start_time; 
}
注意到我把原文中的
 pretranslatemessage(&msg);
替换为了:
 translatemessage(&msg);
 dispatchmessage(&msg);
原因是,可以不仅仅在mfc中使用,而且 pretranslatemessage有局限性,而且可能会造成线程消息阻塞。
        还有一点说明,因为coledatetimespan类的成员函数还有:
gettotalminutes、gettotalhours、gettotaldays,能够实现更大时间段的延时。


        往更小的时间跨度上说,执行毫秒级的延时用gettickcount就行:
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);
}
出处:http://community.csdn.net/expert/topicview1.asp?id=2663023。未做修改,如果需要微秒级的延时中也处理消息,请参照前例修改。

最后,如果还不能满足,那就去做时钟周期的延时吧:

#define nop_count 3//需要自己根据nop及loop的指令周期计算.
__asm {
  mov ecx, nop_count
delay: nop
  loop delay
}
不过,用vc做这个工作是不是有点……

本文关键:VC函数中的延时操作
  相关方案
Google
 

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

go top