I think developing a non-busy-loop timer requires OS-specific functionality to work. The reason you'd want a non-busy-loop is so that your OS doesn't needlessly burn up CPU cycles.
Unless I'm mistaken, the best thing you can do in C++ by itself (besides a busy loop) is std::this_thread::sleep_for
http://en.cppreference.com/w/cpp/thread/sleep_for
But this is not necessarily the most precise, because sleep functions tend to only allow you to give a
minimum time to sleep for, and you can get variable results depend on what your OS's scheduler is doing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include <iostream>
#include <chrono>
#include <thread>
int main()
{
using namespace std::chrono_literals;
for (int i = 0; i < 60; i++)
{
std::this_thread::sleep_for(1s);
std::cout << i << std::endl;
}
}
|
If you want to use external C++ libraries, SFML's sf::Clock can measure time in a similar way to Thomas1965's example
https://www.sfml-dev.org/documentation/2.3/classsf_1_1Clock.php
Note that this counts as a busy-loop.
1 2 3 4 5 6 7 8 9 10
|
sf::Clock clock;
for (int i = 0; i < 60; i++)
{
std::cout << i << std::endl;
while (clock.getElapsedTime().asMilliseconds() < 1000)
{
/* wait, or do other stuff while waiting */
}
clock.restart();
}
|
I think using
waitable timers is the most resource-efficient method to making periodic events happen, but I have not actually used them in my code in C++, so maybe someone else can say if I'm right or wrong.
https://msdn.microsoft.com/en-us/library/windows/desktop/ms687012(v=vs.85).aspx
I'm sure Linux-based systems have some equivalent.
Languages like C# and Java have waitable Timers built in, where they trigger an event on each set interval.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
static void myTimer_Tick(Object myObject, EventArgs myEventArgs)
{
// do stuff in here every 2000 ms, like print out i.
}
static void myFunction()
{
System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();
myTimer.Tick += new EventHandler(myTimer_Tick);
myTimer.Interval = 2000; // event will happen every 2000 ms
myTimer.Start();
}
|
I do not not know if C# or Java have microsecond-precision waitable timers built-in.