朱文昊的中文博客--专注技术,向往自由
提出一种高精度延迟函数的实现,欢迎交流
在Windows系统下,需要延迟一定的时间后继续流程,貌似缺乏这种库函数,MFC提供的延迟函数似乎本质精度无法保证。比如Sleep。在下面提出一种方法,请大家斧正。当然先提出一点,有人认为在Windows系统先不可能获得准确定时,或者把系统挂起来延迟等待不符合多线程编程规范。是的,谢谢您的提醒,但这个讨论中大家就不要再重复这样的观点啦。我们的确需要精确定时,即使我把系统完全占用也在所不惜。不就是几十毫秒嘛
View Code CPP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | // 高精度延迟函数 【开发草稿】 Rev 0.01 /* 注:MSDN中提到的以下问题,本版本程序并未处理!! On a multiprocessor computer, it should not matter which processor is called. However, you can get different results on different processors due to bugs in the basic input/output system (BIOS) or the hardware abstraction layer (HAL). To specify processor affinity for a thread, use the SetThreadAffinityMask function. */ int DelayPrecision(int TimeInMilliSecond) { LARGE_INTEGER Frequency; LARGE_INTEGER CountBegin; LARGE_INTEGER CountNow; LONGLONG DelayCount; LONGLONG EndCount; if (0 != QueryPerformanceFrequency(&Frequency)) { //试算终止计数 DelayCount = Frequency.QuadPart / 1000 * TimeInMilliSecond; if (0 != QueryPerformanceCounter(&CountBegin)) { EndCount = CountBegin.QuadPart + DelayCount; if (EndCount < CountBegin.QuadPart) { //计数器循环回去了 while (1) { if (0 != QueryPerformanceCounter(&CountNow)) { if (CountNow.QuadPart < CountBegin.QuadPart && CountNow.QuadPart > EndCount) { return 1; } } else { break; } } } else { //一般情况 while (1) { if (0 != QueryPerformanceCounter(&CountNow)) { if (CountNow.QuadPart > EndCount) { return 2; } } else { break; } } } } } //如果无法使用高精度定时器,拿Sleep凑合着用吧. Sleep(TimeInMilliSecond); return 0; } |
| 打印文章 | 这篇文章由朱文昊 Albert Zhu于2010年03月8日 下午11:02发表在Cpp 语言。你可以订阅RSS 2.0 也可以发表评论或引用到你的网站。 |


Facebook
Twitter
Picasa
LinkedIn
Youtube
Digg
Buzz