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

Can I replace SDL_GetTicks with std::chrono::high_resolution_clock?

本文关键字:SDL 替换 GetTicks clock resolution chrono high 我可以 std      更新时间:2023-10-16

检查c++中的新东西,我找到了std::chrono库。

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

使用std::chrono::high_resolution_clock的优点是避免在Uint32中存储时间点和时间持续时间。std::chrono库附带了各种各样的std::chrono::duration库,您应该使用它们。这将使代码更具可读性,更少歧义:

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

用于保存时间点和时间持续时间的类型化系统与仅在Uint32中存储内容相比没有开销。除了可能的东西将被存储在Int64代替。但如果你真的想的话,你也可以自定义:

typedef duration<Uint32, milli> my_millisecond;

可以使用以下命令检查high_resolution_clock的精度:

cout << high_resolution_clock::period::num << '/' 
     << high_resolution_clock::period::den << 'n';

SDL_GetTicks返回毫秒,所以完全可以使用std::chrono,但要注意单位转换。它可能不像SDL_GetTicks那么简单。而且,起始点也不会相同。