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

10

在学习C++新东西时,我发现了std::chrono库。

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


我不建议使用,std::chrono 很慢... - Beyondo
2
有没有关于为什么std::chrono会更慢的后续链接或解释? - Spidey
1
SDL_GetTicks实际上使用了SDL_GetTicks64的低32位,在Windows上使用QueryPerformanceCounter()。 std::chrono::steady_clock也是使用QueryPerformanceCounter()实现的。在MSVC上,high_resolution_clock与steady_clock相同。 因此速度是相同的...您可以使用SDL_GetTicks64或std::chrono,效果相同。 - Octo Poulos
2个回答

12
使用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';

2

SDL_GetTicks返回毫秒,因此完全可以使用std::chrono,但要注意必要的单位转换。这可能不像SDL_GetTicks那样简单。另外,起始点将不同。


但我可以简单地创建类似于MyGetTicks的东西来封装转换。规范中是否有最小精度要求? - bcsanches
1
我不知道。但是有一些机会,std::chrono和SDL使用相同的机制,或者至少采用类似的方法。 - Lukior

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接