C – Wait for a specified amount of time without using while C

Wait for a specified amount of time without using while C… here is a solution to the problem.

Wait for a specified amount of time without using while C

I would like to know how to delay time by a few seconds using C without using a while loop. The sample I got is using a while loop.
This works, but I don’t want to use a while loop. Please help

while(clock() < endwaitTime)
    {
        if(! GetFlag())
        {
            print(" Canceled ");
            return ; 
        }
    }

Solution

You can pause your application for a

given number of seconds using sleep(), or you can pause your application for a given number of microseconds using usleep().

You can also explore the blocking property of select() to get microsecond precision pauses. Some apps like to do this, don’t ask me why.

Regarding your while() loop, never do that. It is not suspended. Your application will use 99% of the CPU cycles until the end of time. This is a very stupid approach.

Also, it is best to use time() to get the

current UNIX time and use it as a reference, and difftime() to get the time increment in seconds to use with sleep().

clock() can be problematic because on 32-bit systems this function returns the same number every ~72 minutes, and you often have a endwaitTime value lower than the current return value of clock().

Related Problems and Solutions