Department of Energy Argonne National Laboratory Office of Science NEWTON's Homepage NEWTON's Homepage
NEWTON, Ask A Scientist!
NEWTON Home Page NEWTON Teachers Visit Our Archives Ask A Question How To Ask A Question Question of the Week Our Expert Scientists Volunteer at NEWTON! Frequently Asked Questions Referencing NEWTON About NEWTON About Ask A Scientist Education At Argonne Time Delay in C++
Name: Alice M.
Status: Educator
Age: 40s
Location: N/A
Country: N/A
Date: Around 2001


Question:
How do you do a time delay in C++?



Replies:
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


Click here to return to the Computer Science Archives

NEWTON is an electronic community for Science, Math, and Computer Science K-12 Educators, sponsored and operated by Argonne National Laboratory's Educational Programs, Andrew Skipor, Ph.D., Head of Educational Programs.

For assistance with NEWTON contact a System Operator (help@newton.dep.anl.gov), or at Argonne's Educational Programs

NEWTON AND ASK A SCIENTIST
Educational Programs
Building 360
9700 S. Cass Ave.
Argonne, Illinois
60439-4845, USA
Update: June 2012
Weclome To Newton

Argonne National Laboratory