用c++编写Timer类
Writing a Timer class in c++
由于我在时间等问题上几乎没有经验,在采取下一步行动之前,我想问一下你们
我目前正在用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;
}
- 正在为Xtensa simcall函数编写回调函数
- 在程序中编写脚本来编写和编译代码
- 编写时C++中的输入重定向问题
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- c++多进程编写一个唯一的文件
- 如何用C++编写BFS函数
- 编写代码时C++出现错误:错误 1 错误 C2601:'circle':本地函数定义是非法的
- 如何编写一个使用n倍三元条件语句的C++布尔函数
- 为C++03编译器编写部分unique_ptr,该编译器与较新的编译器在公共代码库上运行
- 如何为 C 型字符串数组编写 getter 和 setter?
- 如何在没有函数的情况下编写此代码并使C++更简单?
- 编写一个函数以使用 n 百分比的 CPU 使用率
- 如何使用OpenCV-C++编写*.mp4视频?
- 3-3. 编写一个程序来计算每个不同单词在其输入中出现的次数
- 我的目标是编写一个程序来计算和存储字符串在字符数组中出现的位置
- 如何编写带有异常的构造函数
- 如何为包含头文件的目标编写生成文件?
- 如何编写一个完美的缩写函数模板?
- 用c++编写Timer类
- 如何为一些类(如timer类)编写单元测试