Hi.
I study C. I need a function or something that will cause delay of given number of seconds, like delay(20) would wait 20 seconds before continuing.
How can I do that in C language?
Thank you.
Hi.
I study C. I need a function or something that will cause delay of given number of seconds, like delay(20) would wait 20 seconds before continuing.
How can I do that in C language?
Thank you.
The techniques to do that are operating system dependent. There is no standard function in the C library to do it.
Under most unix operating systems, there is a function named sleep() that accepts an argument in seconds. It is in a non-standard header <unistd.h>, I think.
Under windows, look up the win32 API function Sleep(). It accepts an argument in milliseconds.
A portable approach is to loop and check the time (using time() or a similar function) until 20 seconds have passed. That is not generally a good idea though, as your program consumes CPU cycles while "delayed" - which is not a good idea, as it affects ability of other applications or the operating system itself to run.
In Unix, you can use unistd.h's sleep() function, as grumpy said, and you can use it for the Windows API, too. Here's a delay function I found, that uses the C standard library:
Please note that this is not the best method, and it consumes a lot of memory.Code:#include <time.h> void wait(float x) { time_t start; time_t current; time(&start); do time(¤t); while (difftime(current,start) < x); }
Originally Posted by The Jargon File
It's probably best to use the OS specific sleep() or Sleep() as these include code that does not race the CPU. Using the loop checking diftime() can cause moments of very high CPU usage... long waits can result in heat problems for poorly cooled systems.