VC自带的SDK中为我们提供了一个Sleep函数,此函数的最小单位为毫秒(既千分之一秒);但在实际的应该中(特别是网络数据传输)我们需要更小的休眠单位(微秒),而系统又没有提供相关API,那么我们如何实现微秒(既十万分之一秒)的休眠呢?
我们知道系统中为我们提供了QueryPerformanceFrequency与QueryPerformanceCounter等相关API,而这些API的时间单位都是微秒及的;这为我们实现微秒休眠提供了思路;为了实用起见我们就直接给出函数代码,代码如下:
// lTime----休眠时间(微秒) // bProcessMsg----休眠时是否处理系统消息 void MSleep( long lTime, bool bProcessMsg ) { LARGE_INTEGER litmp; LONGLONG QPart1,QPart2; double dfMinus, dfFreq, dfTim, dfSpec; QueryPerformanceFrequency(&litmp); dfFreq = (double)litmp.QuadPart; QueryPerformanceCounter(&litmp); QPart1 = litmp.QuadPart; dfSpec = 0.000001*lTime; do { if ( bProcessMsg == true ) { MSG msg; PeekMessage(&msg,NULL,0,0,PM_REMOVE); TranslateMessage(&msg); DispatchMessage(&msg); } QueryPerformanceCounter(&litmp); QPart2 = litmp.QuadPart; dfMinus = (double)(QPart2-QPart1); dfTim = dfMinus / dfFreq; }while(dfTim<dfSpec); }