Files
dl_old/dl/system/dl_time.h
T
2023-12-23 16:39:54 +08:00

115 lines
2.2 KiB
C++

/**
* @file dl_time.h
* @brief 时间相关
*
*
* @version 1.0
* @author lveyou
* @date 23-06-24
*
* @note
*/
#pragma once
#include <string>
#include <chrono>
#include "dl_type.h"
namespace dl
{
class Time
{
friend class System;
public:
Time() :
_delta{ 0 },
_fps{ 0 },
_fpsExpect{ 60 },
_countSec{ 0 },
_countFrame{ 0 }
{
_start = std::chrono::high_resolution_clock::now();
_last = _start;
_delta = 0;
_cacl_expect();
}
/**
* @brief 返回帧间隔
*/
FloatTime GetDelta()
{
return _delta;
}
/**
* @brief 返回fps
*/
unsigned GetFPS()
{
return _fps;
}
/**
* @brief 返回fps
*/
void SetFPS(unsigned fps)
{
_fpsExpect = fps;
_cacl_expect();
}
/**
* @brief 返回游戏运行累计时间
*/
FloatTime GetCurrent()
{
auto current = std::chrono::high_resolution_clock::now();
return std::chrono::duration<FloatTime, std::chrono::seconds::period>
(current - _start).count();
}
//--------------------------------时间戳--------------------------------
/**
@brief 返回时间戳
*/
static time_t GetTimeStamp();
/**
* @brief 时间戳间隔 -> xx:xx:xx
* @note 最多计算到小时
*/
static std::string TimeStampDelta2String(time_t t);
enum class StringFormat
{
HH_MM_SS,
YYYY_MM_DD,
YYYY_MM_DD_HH_MM,
YYYY_MM_DD_HH_MM_SS,
};
/**
* @brief 时间戳 -> xxxx-xx-xx xx:xx:xx 具体参见第二个参数
* @note 非线程安全
*/
static std::string TimeStamp2String(time_t t, StringFormat sf = StringFormat::HH_MM_SS);
private:
FloatTime _delta; //(s)真实间隔时间
FloatTime _deltaExpect; //(s)一帧应该运行的时间
unsigned _fps; //真实帧数
unsigned _fpsExpect; //设置的帧数
FloatTime _countSec; //时间计数(用于fps计算)
unsigned _countFrame; //帧计数(用于fps计算)
std::chrono::nanoseconds _deltaExpectNS;
std::chrono::high_resolution_clock::time_point _start;//起始时间
std::chrono::high_resolution_clock::time_point _last;//上帧时间
//帧末尾,计算这一帧花费时间(但是下一帧才访问到)
void _update();
// 根据期望fps计算期望delta
void _cacl_expect();
// 控制帧率
void _sleep();
};
extern Time* g_time;
}