I need to sleep my program in Windows. What header file has the sleep function?
4 Answers
Use:
#include <windows.h>
Sleep(sometime_in_millisecs); // Note uppercase S
And here's a small example that compiles with MinGW and does what it says on the tin:
#include <windows.h>
#include <stdio.h>
int main() {
printf( "starting to sleep...\n" );
Sleep(3000); // Sleep three seconds
printf("sleep ended\n");
}
-
10"viewed 42374 times" - so obviously many people out there also had this question (and how should I know to prefix "msdn" for my google search when I was mainly doing some Linux/POSIX programming for now?)– mozzbozzOct 8, 2014 at 17:26
SleepEx
function (see http://msdn.microsoft.com/en-us/library/ms686307.aspx) is the best choise if your program directly or indirectly creates windows (for example use some COM objects). In the simples cases you can also use Sleep
.
MSDN: Header: Winbase.h (include Windows.h)
-
1When I include windows.h my compiler gives "error: parameter name omitted" and " error: expected expression before ',' token"– AriyanJul 31, 2010 at 17:40
-
@Snigger Post a short example that demonstrates this, and tell us what compiler you are using.– anonJul 31, 2010 at 17:42
-
#include <windows.h> void writeData(result * res ,char OUT){ } int main(){ return 1; } gives " error: expected ')' before '' token" and I'm using GCC (mingw)– AriyanJul 31, 2010 at 17:48
-
@Snigger Your program does not declare the type "result" - nothing to do with windows or Sleep. and it does not give the error messages you said it did (it gives different ones).– anonJul 31, 2010 at 17:58
-
6This is NOT discussion/comments on my answer. This is an entirely tangential discussion that belongs in its own answer.– abelenkyJul 31, 2010 at 19:55
Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.
void sleep(unsigned int mseconds)
{
clock_t goal = mseconds + clock();
while (goal > clock())
;
}
Note that the name sleep
for this function is misleading, since the CPU will not be sleeping at all.
-
171. This does not answer the poster's questions 2. This is just wrong because it is still a busy loop (with or without a 'for' loop). Jan 7, 2015 at 13:30
-
1up vote. I was searching for some sleep function in windows C, except Sleep(). This is working fine. thanks.– rashokMar 20, 2015 at 16:35
-
12This is not sleep, this is "keep busy in a tight loop", and put extra burden on CPU anyway. Sleep releases the CPU to do other things.– LargatoDec 8, 2016 at 18:53
-
up vote too. Althogh it keeps CPU busy but this is much more accurate than
Sleep()
.– ZR HanJun 9, 2022 at 5:21