Handling an update loop using C++ Chrono?

风格不统一 提交于 2019-11-28 09:22:35

When using std::chrono you should avoid, as much as possible, casting durations or converting durations to raw integral values. Instead you should stick with the natural durations and take advantage of the type safety that duration types provide.

Below is a series of specific recommendations. For each recommendation I'll quote lines of your original code and then show how I would re-write those lines.


const milliseconds kMaxDeltatime((int)((1.0f / 60.0f) * 1000.0f)); // It's hard to tell, but this seems to come out to some tiny number, not what I expected!

There's no reason to do this sort of computation with manual conversion constants. Instead you can do:

typedef duration<long,std::ratio<1,60>> sixtieths_of_a_sec;
constexpr auto kMaxDeltatime = sixtieths_of_a_sec{1};

frameTime = duration_cast<milliseconds>(Clock::now() - mLastEndTime); // Is this the best way to get the delta time, with a duration cast?

You can just keep the value in its native type:

auto newEndTime = Clock::now();
auto frameTime = newEndTime - mLastEndTime;
mLastEndTime = newEndTime;

while (frameTime.count() > 0) // Is this the best way to measure greater than 0 milliseconds?

Instead use:

while (frameTime > milliseconds(0))

engine->Update((long)mDeltaTime.count()); // From here, it's so much easier to deal with code in longs. Is this the best way to shove a long through my code?

It's best to write code that uses chrono::duration types throughout, rather than to use generic integral types at all, but if you really need to get a generic integral type (for example if you must pass a long to a third-party API) then you can do something like:

auto mDeltaTime = ... // some duration type

long milliseconds = std::chrono::duration_cast<std::duration<long,std::milli>>(mDeltaTime).count();
third_party_api(milliseconds);

Or:

auto milliseconds = mDeltaTime/milliseconds(1);

And to get the delta you should do something like:

typedef std::common_type<decltype(frameTime),decltype(kMaxDeltatime)>::type common_duration;
auto mDeltaTime = std::min<common_duration>(frameTime, kMaxDeltatime); 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!