Reputation: 99
I'm trying to simulate a real life scenario that takes actual time using C++; I am using a for loop to break up time into five-minute increments.
I want to know if there is any way to tell the program to only execute through one step of the for loop every second? This way the program would become "watchable".
Upvotes: 0
Views: 209
Reputation: 16168
Get the current time and add the frequency, the perform you actin and wait until the calculated time. Like so.
#include <thread>
#include <chrono>
//...
while(whatever_condition()) {
auto next=std::chrono::system_clock::now()
+std::chrono::seconds(1);
do_whatever();
std::this_thread::sleep_until(next);
}
http://en.cppreference.com/w/cpp/thread/sleep_until
Note using the plain "sleep" and "usleep" functions are nonstandard, and will NOT take into account the amount of time the operation takes.
EDIT:
This is a c++11 solution, however if don't have C++11 boost provides this functionality too for C++98 and 03. I believe that is still preferable to using sleep
Upvotes: 6
Reputation:
How important is it that it runs at a consistent rate? sleep()
is one possible method of doing this, but sleep
is pretty poor at delivering exact time slices. Games, of course, need to do this all the time so games programmers have explored a whole variety of ways of doing this, you can find a discussion of how to implement a game loop here. The central theory is to regularly check the timer and update according to produce the desired number of frames-per-second.
Upvotes: 0
Reputation: 6858
With sleep you can have the program wait. I don't know if this is what you intend. So to wait one second, you type:
sleep(1000)
Upvotes: 0