Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep() vs _sleep() functions

Currently, I am 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 newer version such as Visual Studio 2015 or 2017.

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

I didn't find the equivalent documentation for the old _sleep() function and I wonder if both functions behave exactly identical ? This MSDN post makes me wondering if the only differences are in the types of the argument ?

Thanks in advance for your answers.

like image 444
mlel Avatar asked Mar 21 '18 15:03

mlel


1 Answers

As RbMm mentioned, _sleep had been implemented as a very thin wrapper around Sleep:

void __cdecl _sleep(unsigned long dwDuration)
{

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

}

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

#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

So it appears both _sleep and Sleep sleep for the specific number of milliseconds.
_sleep is a MSVC CRT function, and Sleep is a Windows API.
So in MSVC they should be interchangeable.

One minor difference is that in case of a 0 argument, _sleep sleeps for 1ms whereas Sleep doesn't sleep at all.

like image 147
rustyx Avatar answered Oct 19 '22 19:10

rustyx