Peter Ammon said:
You can use the localtime() function combined with the time() function
to get the current time. You can poll on those until the delay is up.
Be aware that both those functions are allowed to fail.
Something like that is probably the only *portable* way to delay for a
specified time interval. You don't really need localtime(); you can
do it with time() and difftime(). For example, the following program
should sleep for about 3 seconds:
#include <stdlib.h>
#include <time.h>
int main(void)
{
time_t start_time = time(NULL);
while (difftime(time(NULL), start_time) < 3.0) {
;
}
return 0;
}
I've omitted any error checking. Even if it works, the amount of time
it sleeps is likely to be imprecise; the standard doesn't specify the
precision of the time() function, and one second is typical.
On many systems, this technique has some severe drawbacks. On a Linux
or other Unix-like system, or on any multi-process system, the
continuous polling is likely to cause the program to gobble up nearly
100% of the CPU time. What you almost certainly really want your
program to do is go to sleep for a specified interval, allowing other
processes to run until your program wakes up.
This concern is not addressed by the C standard because the standard
is not concerned with multi-processing systems, but it's something you
should think about.
There are system-specific functions that will do exactly what you
want. You can probably get more information about such functions from
your system's documentation or, if that fails, by asking in a
system-specific newsgroup such as comp.unix.programmer.