检查来自 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?
对比:
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/