The SDK provided by VC provides us with a Sleep function. The minimum unit of this function is Millisecond (1‰ s). However, in practice (especially network data transmission) we need a smaller sleep unit (microseconds), and the system does not provide relevant APIs. How can we achieve sleep in microseconds (one thousandth second?
We know that the system provides QueryPerformanceFrequency, QueryPerformanceCounter, and other related APIs. The time units of these APIs are in microseconds. This provides us with an idea to implement microsecond sleep; for the sake of practicality, the function code is provided directly. The Code is as follows:
// LTime ---- sleep time (microseconds) // bProcessMsg ---- whether to process system message 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, PM_REMOVE); TranslateMessage (& msg ); dispatchMessage (& msg);} QueryPerformanceCounter (& litmp); QPart2 = litmp. quadPart; dfMinus = (double) (QPart2-QPart1); dfTim = dfMinus/dfFreq;} while (dfTim <dfSpec );}