Although many implementations have the time
function return the current time in seconds, there is no guarantee that every implementation will do so (e.g. some may return milliseconds rather than seconds). As such, a more portable solution is to use the difftime
function.
difftime
is guaranteed by the C standard to return the difference in time in seconds between two time_t
values. As such we can write a portable time delay function which will run on all compliant implementations of the C standard.
#include <time.h>
void delay(double dly){
/* save start time */
const time_t start = time(NULL);
time_t current;
do{
/* get current time */
time(¤t);
/* break loop when the requested number of seconds have elapsed */
}while(difftime(current, start) < dly);
}
One caveat with the time
and difftime
functions is that the C standard never specifies a granularity. Most implementations have a granularity of one second. While this is all right for delays lasting several seconds, our delay function may wait too long for delays lasting under one second.
There is a portable standard C alternative: the clock
function.
The clock
function returns the implementation’s best approximation to the processor time used by the program since the beginning of an implementation-defined era related only to the program invocation. To determine the time in seconds, the value returned by the clock
function should be divided by the value of the macro CLOCKS_PER_SEC
.
The clock
function solution is quite similar to our time
function solution:
#include <time.h>
void delay(double dly){
/* save start clock tick */
const clock_t start = clock();
clock_t current;
do{
/* get current clock tick */
current = clock();
/* break loop when the requested number of seconds have elapsed */
}while((double)(current-start)/CLOCKS_PER_SEC < dly);
}
There is a caveat in this case similar to that of time
and difftime
: the granularity of the clock
function is left to the implementation. For example, machines with 32-bit values for clock_t
with a resolution in microseconds may end up wrapping the value returned by clock
after 2147 seconds (about 36 minutes).
As such, consider using the time
and difftime
implementation of the delay function for delays lasting at least one second, and the clock
implementation for delays lasting under one second.
A final word of caution: clock
returns processor time rather than calendar time; clock
may not correspond with the actual elapsed time (e.g. if the process sleeps).