10

Checking new stuff from C++, I have found the std::chrono library.

I am wondering if std::chrono::high_resolution_clock could be a good replacement for SDL_GetTicks?

bcsanches
  • 2,362
  • 21
  • 32
  • I don't recommend it, std::chrono much slower... – Beyondo Jun 23 '18 at 11:15
  • 2
    Any follow up link or explanation on why `std::chrono` would be slower? – Spidey Feb 17 '19 at 15:44
  • 1
    SDL_GetTicks is actually using the low 32 bits of SDL_GetTicks64, which on windows is using QueryPerformanceCounter(). std::chrono::steady_clock is implemented using QueryPerformanceCounter() as well. On MSVC, high_resolution_clock is the same as steady_clock. So it's the same speed... You can use SDL_GetTicks64 or std::chrono, same thing. – Octo Poulos Jan 05 '22 at 15:50

2 Answers2

12

The advantage of going with std::chrono::high_resolution_clock is to keep away from storing time points and time durations in a Uint32. The std::chrono library comes with a wide variety of std::chrono::durations that you should use instead. This will make code more readable, and less ambiguous:

Uint32 t0 = SDL_GetTicks();
// ...
Uint32 t1 = SDL_GetTicks();
// ...
// Is t1 a time point or time duration?
Uint32 d = t1 -t0;
// What units does d have?

vs:

using namespace std::chrono;
typedef high_resolution_clock Clock;
Clock::time_point t0 = Clock::now();
// ...
Clock::time_point t1 = Clock::now();
// ...
// Is t1 has type time_point.  It can't be mistaken for a time duration.
milliseconds d = t1 - t0;
// d has type milliseconds

The typed system for holding points in time and time durations has no overhead with respect to just storing things in a Uint32. Except maybe that things will be stored in an Int64 instead. But even that you could customize if you really wanted to:

typedef duration<Uint32, milli> my_millisecond;

You can inspect the precision of the high_resolution_clock with:

cout << high_resolution_clock::period::num << '/' 
     << high_resolution_clock::period::den << '\n';
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
2

SDL_GetTicks returns milliseconds so it is totally possible to use std::chrono instead, but mind the units conversion necessary. It may not be as simple as SDL_GetTicks. Also, the starting point won't be the same.

Lukior
  • 59
  • 3
  • But I can simple create something like MyGetTicks to encapsulate the conversion. Is there any minimum precision requirement in the spec? – bcsanches Dec 27 '12 at 14:09
  • 1
    Not that I know. But there is some chances that std::chrono and SDL uses the same mechanisms, or at least a similar approach. – Lukior Dec 27 '12 at 14:13