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

标签 c++ c++11 sdl

检查来自 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/

相关文章:

c++ - 在 C++ 中链接 SDL_ttf 库

c - fscanf 正在崩溃程序

c++ - 嵌套 Ifs VS 2 个独立的 IFs - 性能方面?

c++ - 角度的 Slerp 插值结果为 -nan(ind)

c++ - 了解 std::regex 声明:运行时的 regex_error 异常

c++ - 从成员函数返回一个只能 move 的对象

C++ 错误 : request for member '...' in 'grmanager' which is of non-class type 'GraphicsManager'

c++ - 删除动态 vector 数组

c++ - 非成员函数模板什么时候有内部链接?

c++ - 使用模板基类消除工厂类派生类冗余的简洁方法