- #1
DrKareem
- 101
- 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.
Orefa said:Wait approximately 5 seconds with something like this:
for (time_t t = time() + 5; time() < t; ) {}
Oh right, that should have been time(0) instead of just time().DrKareem said:error C2660: 'time' : function does not take 0 parameters
DrKareem said:i mean that the test programme should cout my first name, delay 3 seconds and the output my last name, but it delays 3 seconds then outputs my full name. weird.
Sure it is -- if you remember to convert using CLOCKS_PER_SEC! (I think that's how the macro is spelled)This varies from system to system so the pause duration is not consistent across systems (if consistency matters).
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: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.
Never, ever do something like this. Sending the CPU into a busy loop is a very, very bad thing to do.Orefa said:for (time_t t = time() + 5; time() < t; ) {}
Time delay in C++ refers to pausing or delaying the execution of a program for a specified amount of time. This is commonly used in applications where timing is critical, such as games or simulations.
Time delay in C++ can be implemented using the sleep()
function from the ctime
library. This function takes in the number of seconds to pause the program for and can also be used to pause for fractions of a second using the usleep()
function.
Time delay in C++ is used to pause the program for a specific amount of time, whereas time measurement is used to track the elapsed time of a program or a specific part of a program. Time measurement can be done using the clock()
function from the ctime
library.
While time delay can be used for basic timing in C++, it is not recommended for precise timing as it is affected by factors such as system load and other running processes. For precise timing, it is better to use libraries such as chrono
or boost::timer
.
Yes, time delay in C++ can be platform-dependent as it relies on the system clock and the implementation of the sleep()
function may vary across different operating systems. It is important to consider this when writing cross-platform code.