我可以用std :: chrono :: high_resolution_clock替换SDL_GetTicks吗?

bcs*_*hes 5 c++ sdl c++11

从C++中检查新东西,我找到了std :: chrono库.

我想知道std :: chrono :: high_resolution_clock是否可以替代SDL_GetTicks?

How*_*ant 10

与之相关的优点std::chrono::high_resolution_clock是远离存储时间点和持续时间Uint32.该std::chrono库附带了各种各样的std::chrono::durations,你应该使用它们.这将使代码更具可读性,并且不那么模糊:

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?
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

用于在时间和持续时间内保持点的类型系统没有关于仅仅存储事物的开销Uint32.除非事情将被存储在一个Int64代替.但即使你可以自定义,如果你真的想:

typedef duration<Uint32, milli> my_millisecond;
Run Code Online (Sandbox Code Playgroud)

您可以检查high_resolution_clockwith 的精度:

cout << high_resolution_clock::period::num << '/' 
     << high_resolution_clock::period::den << '\n';
Run Code Online (Sandbox Code Playgroud)