用c++编写Timer类

Writing a Timer class in c++

本文关键字:Timer 编写 c++      更新时间:2023-10-16

由于我在时间等问题上几乎没有经验,在采取下一步行动之前,我想问一下你们
我目前正在用SDL编写一个游戏引擎,并使用函数SDL_GetTicks()在GameLoop中计算我的deltaTime
由于我需要一个定时器功能来控制资产的生存期(当资产在特定时间内没有使用时,我想从缓存中删除它),我寻找了一些实现方法
我发现<chrono>标头适合该任务,但记住我已经在内部为deltaTime使用了SDL_GetTicks()

对我来说,使用两个不同的计时器可能会引起一些问题
有什么我应该注意的吗,或者只是坚持使用SDL_GetTicks()来解决所有的时间问题?

p.S:如果这属于"游戏开发"部分,我很抱歉,但我认为这是一个普遍的问题

如果对您有帮助(我真的不知道),您可以通过围绕SDL_GetTicks()构建一个自定义时钟来将其集成到std::chrono系统中,如下所示:

#include <chrono>
struct GetTicks_clock
{
    using duration   = std::chrono::milliseconds;
    using rep        = duration::rep;
    using period     = duration::period;
    using time_point = std::chrono::time_point<GetTicks_clock, duration>;
    static const bool is_steady = true;
    static time_point now() noexcept {return time_point(duration(SDL_GetTicks()));}
};
int
main()
{
    auto t0 = GetTicks_clock::now(); // has type GetTicks_clock::time_point
    // do something here
    auto t1 = GetTicks_clock::now(); // has type GetTicks_clock::time_point
    auto delta_ms = t1 - t0;  // has type std::chrono::milliseconds
}

现在,您可以像使用std::chrono::steady_clock一样使用GetTicks_clock。这为您提供了一个基于现有SDL_GetTicks()的类型安全的计时基础设施(持续时间和时间点)。您甚至可以使用自定义时钟睡觉或等待:

std::this_thread::sleep_until(GetTicks_clock::now() + std::chrono::seconds(1));

听起来std::chrono通常适用于您,但您不能使用if作为刻度计数,因为您使用SDL_GetTicks()作为该信息。那么,为什么不能将std::chrono::duration与该函数的结果一起使用呢?

对我来说,使用两个不同的计时器可能会引起一些问题。有什么我应该注意的吗,或者只是简单地使用SDL_GetTicks()来解决所有的时间问题?

除非我遗漏了什么,否则使用std::chrono::duration不会涉及超过1个计时器(即,您仍然只使用SDL_GetTicks函数来获取计时)。您只是使用std::chrono::duration来存储SDL_GetTicks返回的结果的表示。

示例

#include <chrono>
#include <iostream>
// This function is only for illustration, I don't know what type
// the real function returns
long long SDL_GetTicks()
{
    return 1234567890;
}
int main()
{
    std::chrono::milliseconds elapsedTime(0);
    elapsedTime += std::chrono::milliseconds(SDL_GetTicks());
    std::cout << elapsedTime.count() << "n";
    return 0;
}