The standard library header chrono (available since C++11) provides various clock and duration types you can use to compute time intervals (in theory -- see my footnote and the comments). You probably want steady_clock
. Your periodic update method would look something like:
auto currentTime = std::chrono::steady_clock::now();
auto elapsed = previousTime - currentTime;
... do stuff with elapsed time...
float elapsed_f = elapsed.count();
previousTime = currentTime;
(where previousTime
is a member or some other persistent storage for the time point). The subtraction of two time points will result in a duration
object. This site also contains a more concrete example of using the clock mechanism.
If steady_clock
isn't fine-grained enough for you, you can look at high_resolution_clock
. However, it's important to test if the clock that backs the high resolution clock is monotonically increasing (check the is_steady
member function), because it's not guaranteed to be so.
Note that as discussed in the comments, chrono
has some issues which tend to make it less than ideal for games -- some of them are due to the wording of the standard providing lots of leeway, some of them are just down to poor implementations. Even though it would not be a great answer to your question, using platform-specific timer mechanisms (possibly wrapped up on your own abstraction) are likely the better solution to your problem.