在学习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那样简单。另外,起始点将不同。
std::chrono
会更慢的后续链接或解释? - Spidey