Time Delay in C++: A Simple Solution for a Few Seconds Delay

Click For Summary

Discussion Overview

This discussion revolves around implementing a time delay in C++ programming, exploring various methods and functions available for achieving this. Participants discuss both standard and platform-specific approaches, including considerations for portability and accuracy.

Discussion Character

  • Technical explanation
  • Debate/contested
  • Mathematical reasoning

Main Points Raised

  • One participant suggests using a loop for a time delay, but acknowledges that this method may yield inconsistent results across different computers.
  • Another participant proposes using C time functions such as "time" and "clock" from the "ctime" header for implementing delays.
  • A method involving a loop with "time()" is presented, but concerns about accuracy and CPU usage are raised.
  • Some participants mention the use of the Sleep function in Windows and its equivalent in Unix, noting that these are more efficient than busy-wait loops.
  • There is a discussion about the inclusion of specific headers for different operating systems, such as for Windows and for Unix.
  • One participant shares a code snippet that delays execution but experiences unexpected output behavior, prompting further discussion on output buffering and flushing.
  • Concerns are raised about the portability of custom delay implementations and the potential for compiler optimizations to affect timing accuracy.
  • Some participants argue against busy-wait loops, emphasizing the importance of using system calls for delays to avoid unnecessary CPU load.
  • There is mention of using platform-dependent code blocks to create a wrapper function for sleep, allowing for easier portability across systems.

Areas of Agreement / Disagreement

Participants express a range of views on the best methods for implementing time delays in C++. While some agree on the use of system-specific functions like Sleep, others caution against busy-wait loops. The discussion reflects multiple competing approaches and does not reach a consensus on a single best method.

Contextual Notes

Participants highlight limitations regarding the granularity of timing functions, potential inconsistencies across different systems, and the impact of compiler optimizations on custom delay implementations.

Who May Find This Useful

This discussion may be useful for C++ programmers seeking to implement time delays in their applications, particularly those interested in understanding the implications of different methods across various operating systems.

DrKareem
Messages
101
Reaction score
1
Hello. I'm wondering how to make a time delay of a few seconds using C++. The simplest way that came up to my mind is just to make loop for a few millions time or so, but the delay would change from computer to computer.
 
Technology news on Phys.org
You could simply use the ordinary C time functions. See "time" and "clock" in the "ctime" header.
 
Wait approximately 5 seconds with something like this:

for (time_t t = time() + 5; time() < t; ) {}

If you need more accuracy, use clock_t and clock() instead, along with the CLK_TCK value. If you are programming for Windows, use Sleep(5000) to let the process sleep for 5000 milliseconds without wasting all those CPU cycles. For other OSes, check the documentation for a similar function.
 
sleep(<time in ms>) is the standard way of doing it.
 
Are those functions in C or C++? If the latter, what library should I include?
 
Under Unix sleep is in unistd.h. I'm not sure about windows.
 
No such library in windows. There is a time.h windows though, but no sleep function. Is there a way to view the source file?
 
Orefa said:
Wait approximately 5 seconds with something like this:

for (time_t t = time() + 5; time() < t; ) {}


error C2660: 'time' : function does not take 0 parameters
 
I found this piece of code on the net:

time_t start_time, cur_time;

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

where n is the number of seconds. when i run my programme, it first does the delay, then run the rest.

i mean that the test programme should count my first name, delay 3 seconds and the output my last name, but it delays 3 seconds then outputs my full name. weird.
 
  • #10
Ugh, I did a google search and it said windows.h
 
  • #11
void sleep( clock_t wait )
{
clock_t goal;
goal = wait + clock();
while( goal > clock() )
;
}

Found the sleep function on the net, but still, the programme does the delay, then outputs the full name.

*shrugs*
 
  • #12
DrKareem said:
error C2660: 'time' : function does not take 0 parameters
Oh right, that should have been time(0) instead of just time().

But are you using Unix or Windows? Because #include <windows.h> with Sleep(milliseconds) in Windows or #include <unistd.h> with sleep(milliseconds) in Unix is simpler and more reliable. The sleep function you show that uses clock_t instead of time_t does not count in seconds or milliseconds but in system clock ticks. This varies from system to system so the pause duration is not consistent across systems (if consistency matters).

DrKareem said:
i mean that the test programme should count my first name, delay 3 seconds and the output my last name, but it delays 3 seconds then outputs my full name. weird.

Your first name may be in count's output buffer but it won't show until the buffer is flushed. Try using count.flush() to force it out before the pause.
 
  • #13
I have both windows and linux, but i usually programme on windows since I'm new to linux. Flushing the buffer did take care of the problem. Thanks guys!
 
  • #14
This varies from system to system so the pause duration is not consistent across systems (if consistency matters).
Sure it is -- if you remember to convert using CLOCKS_PER_SEC! (I think that's how the macro is spelled)
 
  • #15
Edit: the C standard does not require any fine granularity for clock(). It has to "tick" at least once per second, even if CLOCKS_PER_SEC is 1000000. So if you choose 50 ms depending on the implementation of C/C++ you may still get 1 full second.

Sleep(DWORD milliseconds) is the Windows api call you want, in
windows.h Consider using it.

Implementing a roll-your-own time delay means the time delay will not port - and this may mean going from Windows XP on a PIII 500MHz to Windows XP on a P4 3.2GHz will cause the code not to behave correctly.

Plus, turning on optimization may allow a compiler optimize away a few of these kinds of homegrown loops

Use the api - all time delay calls are hardware/OS dependent anyway, so you are not losing portability. You are probably gaining some.
 
Last edited:
  • #16
And if you really want, demarcate a platform-dependent block of your source code, and define your own "my_sleep" which is merely a wrapper for whatever the best method of sleeping is on a given system.

(So, when porting, the only code that ought to need changing is the code in this block)
 
  • #17
Sleep(milliseconds) in c++

You can simply use the Sleep(milliseconds) function which must have windows.h included...
I'm a little late, but just in case you still check it a year after the fact :)

Example:

#include <windows.h>
Sleep(1000);
//this will sleep for 1 second (1000) milliseconds
//It of course needs to be put into some function, but I'm a smidge too lazy :)
 
  • #18
Orefa said:
But are you using Unix or Windows? Because #include <windows.h> with Sleep(milliseconds) in Windows or #include <unistd.h> with sleep(milliseconds) in Unix is simpler and more reliable.
The sleep function in Unix is in seconds. This might create a problem if the Windows program is ported to Unix. A better solution might be to use the Posix usleep function, which takes integer microseconds as an argument (but the time needs to be less than 1 million microseconds).

Orefa said:
for (time_t t = time() + 5; time() < t; ) {}
Never, ever do something like this. Sending the CPU into a busy loop is a very, very bad thing to do.
 
  • #19
Let's not resurrect ancient threads. Thanks.

- Warren
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 8 ·
Replies
8
Views
2K
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 5 ·
Replies
5
Views
5K
  • · Replies 4 ·
Replies
4
Views
5K
  • · Replies 13 ·
Replies
13
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K