从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';

关于c++ - 我可以用std::chrono::high_resolution_clock替换SDL_GetTicks吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14055866/

10-11 22:43
查看更多