Handling an update loop using C++ Chrono?

后端 未结 1 1531
有刺的猬
有刺的猬 2020-12-09 21:43

I\'m definitely a bit lost with the new C++ chrono library.

Here I have an update loop. It runs two operations:

engine.Update()
engine.Render()
         


        
1条回答
  •  时光说笑
    2020-12-09 22:15

    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> sixtieths_of_a_sec;
    constexpr auto kMaxDeltatime = sixtieths_of_a_sec{1};
    

    frameTime = duration_cast(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>(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::type common_duration;
    auto mDeltaTime = std::min(frameTime, kMaxDeltatime); 
    

    0 讨论(0)
提交回复
热议问题