Functions Sleep () vs _sleep ()

I am currently working on an old project developed (in C and C ++) for Windows with Visual Studio 2010 or less. We would like to update it for a newer version, for example Visual Studio 2015 or 2017.

I found that the _sleep () function is no longer supported by Microsoft , and I will use the Sleep () function instead .

I have not found equivalent documentation for the old _sleep () function, and I wonder if both functions behave exactly the same? This MSDN message makes me wonder if there are only differences in argument types?

Thanks in advance for your answers.

+6
source share
1 answer

As mentioned in RbMm, it _sleepwas implemented as a very thin shell around Sleep:

void __cdecl _sleep(unsigned long dwDuration)
{

    if (dwDuration == 0) {
        dwDuration++;
    }
    Sleep(dwDuration);

}

To confirm, we can check it. Fortunately, it's easy to check:

#include <iostream>
#include <chrono>
#include <windows.h>
#include <stdlib.h>

using namespace std::chrono_literals;

int main() {
    auto tm1 = std::chrono::system_clock::now();
    _sleep(250);
    auto tm2 = std::chrono::system_clock::now();
    Sleep(250);
    auto tm3 = std::chrono::system_clock::now();
    std::cout << "_sleep took " << (tm2-tm1)/1ms << " ms, Sleep took " << (tm3-tm2)/1ms << " ms\n";
}

Output:

_sleep took 250 ms, Sleep took 250 ms

Thus, for a certain number of milliseconds it appears as _sleepwell as Sleepsleep.
_sleepis the MSVC CRT function, and Sleepis the Windows API.
Therefore, they must be interchangeable in MSVC.

One minor difference is that in the case of the argument 0 _sleepsleeps for 1ms, while they Sleepdo not sleep at all.

+3
source

All Articles