Kapteyn's Star said:
Is this related to what you say?
#include <stdlib.h>
#include <time.h>
int delay(int sec)
{
time_t t0;
time_t t1;
time_t inv = -1;
for(t0= t1= time(0);
t0 != inv && t1 != inv && sec > difftime(t1, t0);
t1= time(0))
{
;
}
return t0 == inv || t1 == inv;
}
int main()
{
if(delay(3))
{
return EXIT_FAILURE;
}
return 0;
}
It seems to work...
Yes, it *seems* to work, but it has several practical problems.
The resolution of the time() function is not specified by the
standard. If it's 1 second (as is typical), then delay(2) could delay
for any length of time from just over 2 seconds to just over 3 seconds
("just over" because of overhead). If the resolution is anything
else, that will affect the behavior.
Furthermore, if you call diff(3), then your program will spend roughly
3 seconds doing nothing useful, but doing it in an extraordinarily
inefficient manner. It will repeatedly call the time() and difftime()
functions just as quickly as it can, consuming CPU time to do it.
This might be acceptable on an embedded system with no other programs
running, but on a typical multi-user system, or even on a single-user
multi-processing system, it could have serious effects on system
performance.
Sleeping for a specified length of time is something that *can* be
done in portable standard C, but only very badly. Or it can (almost
always) be done very simply and straightforwardly with some
non-portable call, with minimal overhead and much better precision.
If you have a real need to sleep for 3 seconds, it's likely (but not
certain) that your program is performing some other system-specific
action as well; in that case, using a system-specific call won't
result in any additional loss of portability.