Time Delay in C++
Name: Alice M.
Date: Around 2001
How do you do a time delay in C++?
There are several approaches to a time delay.
The simplest, easiest, and least reliable is to do a series of nested loops,
for(x = 0; x < 2000; x++)
for(y = 0; y < 2000000; y++)
Then adjust x and y until the time is about right. This is not reliable
because the delay will be different on different machines.
A better way is to use the time function, for example, to delay 3 seconds:
time_t start_time, cur_time;
while((cur_time - start_time) < 3);
This works well, but will not allow delays in anything other than 1 second
If you need finer resolution, you can use the clock function:
clock_t start_time, cur_time;
start_time = clock();
while((clock() - start_time) < 3 * CLOCKS_PER_SEC)
Unfortunately, the clock function does not work with all compilers and
operating systems. If it returns -1, the clock function is not available.
There are several other functions that can be used. For Windows computers,
there are _ftime, Sleep(), and QueryPerformanceCounter() functions, as well
as the sytem timer.
I hope this helps.
Click here to return to the Computer Science Archives
Update: June 2012