Ask A Scientist©

Computer Science Archive


Time Delay in C++


name         Alice M.
status       educator
age          40s

Question -   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 example:

int x,y;
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;

         time(&start_time);
         do
         {
                 time(&cur_time);
         }
         while((cur_time - start_time) < 3);

This works well, but will not allow delays in anything other than 1 second
intervals.


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.
--Eric Tolman
=========================================================



Back to Computers Ask A Scientist Index
NEWTON Homepage Ask A Question

NEWTON is an electronic community for Science, Math, and Computer Science K-12 Educators.
Argonne National Laboratory, Division of Educational Programs, Harold Myron, Ph.D., Division Director.