利用for循环实现程序的延时
来源:互联网 发布:人知将死 其言也善后句 编辑:程序博客网 时间:2024/05/15 01:38
程序中延时的方法很多,如直接调用Sleep函数
也可用for循环来实现一个延时,例如:
int m=0;
for (int x=0;x<20000;x++)
{
for (int y=0;y<20000;y++)
{
m++;
}
}
也可用下面这个函数
/*
功能:带windows消息处理的毫秒界别延时
参数:
ms:延迟时间(单位:毫秒)
*/
bool CTools::delayMsMessage(const unsigned int ms)
{
//局部变量
unsigned int preTickMs = 0;
unsigned int nextTickMs = 0;
unsigned int counter = 0;
MSG msg;
DebugInfo * debugInfo = DebugInfo::getInstance();
//获取当前时刻
if( CTools::getTickCountMs(preTickMs) == false )
{
debugInfo->print("CTools::delayMsMessage,获取当前时刻失败\n");
return false;
}
nextTickMs = preTickMs;
//循环等待
while( (nextTickMs - preTickMs) <= ms )
{
//内部计数器递增
counter++;
//处理消息队列
if( PeekMessage(&msg, NULL, 0, 0, PM_REMOVE) )
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
//再次查询时刻
if( CTools::getTickCountMs(nextTickMs) == false )
{
debugInfo->print("CTools::delayMsMessage,获取当前时刻失败\n");
return false;
}
}
return true;
}
其中,
/*
功能:获取当前时刻(精度:毫秒)
参数:
ms:当前时刻(单位:毫秒)
说明:
由于计数器数据位可以达到64bit;
计数的时间可以达到1千万天。
而其实也可以转成用低32bit来计数;
计数的时间可以达到1000秒左右。
其实用低32bit就能满足要求,常用的
定时不会超过1分钟。
*/
bool CTools::getTickCountMs(unsigned int &ms)
{
//局部变量
LARGE_INTEGER freq;
LARGE_INTEGER time;
unsigned int iFreq = 0;
unsigned int iTime = 0;
DebugInfo * debugInfo = DebugInfo::getInstance();
//为了尽可能保留精度,使用了双精度
//浮点数来进行运算
double fTime = 0.0;
//获取时钟频率
if( !QueryPerformanceFrequency(&freq) )
{
debugInfo->print("CTools::getTickCountMs,不能获取时钟频率\n");
return false;
}
//获取时钟计数器数值
if( !QueryPerformanceCounter(&time) )
{
debugInfo->print("CTools::getTickCountMs,不能获取时钟计数值\n");
return false;
}
//将计数值转换成微秒数
fTime = (float)time.LowPart;
fTime /=(float)freq.LowPart;
fTime *= 1000.0;
ms = (unsigned int)fTime;
return true;
}
- 利用for循环实现程序的延时
- for循环实现C语言精确延时
- for循环实现C语言精确延时
- 利用for循环实现的隔行变色
- for循环 延时
- 如何正确计算多重循环延时程序的延时时间
- 利用stm32f103的TIM2实现精确延时
- for循环用于延时例子
- cocos2dx schedule可延时的for循环 scheduleonce的问题
- XSLT - 利用template实现for循环
- XSLT - 利用template实现for循环
- 利用for循环嵌套实现九九乘法表
- 延时程序实现的Led灯闪砾效果
- 利用定时器1延时1秒的程序(c51语言)
- python下sched实现延时或者循环的用法
- Keil代码中for循环延时问题
- for循环中加入延时函数setTimeout
- 利用timeGetTime()实现延时操作
- Dev gridcontrol获取选定行,指定列单元格的内容
- OpenCV学习(五)平滑滤波
- Cocos2dx 3.0rc 创建工程、交叉编译至android 的懒人脚本
- Struts2拦截器的实例
- 约瑟夫环:用java解决的一种办法
- 利用for循环实现程序的延时
- poj 2771 Guardian of Decency (二分图求最大独立集)
- 参数化查询为什么能够防止SQL注入
- 输入函数的细节
- Java 基础 - 常见运算符
- 二进制位的操作
- J - Min Number
- jquery $(document).ready() 与window.onload的区别
- ArcGIS 10.1 for Server 如何注册数据库(上)