# Utils/Time.hpp 头文件解析
## 概述
本头文件提供跨平台的时间处理工具,主要用于时间戳生成、格式转换及时区处理,服务于3D打印领域的G代码生成、文件版本管理等场景。
## 核心功能
### 1. 时间获取
```cpp
time_t get_current_time_utc(); // 秒级UTC时间
time_t get_current_milliseconds_time_utc(); // 毫秒级UTC时间
- 线程安全:明确标注应保证线程安全
- 应用场景:
- 精确计时(如打印耗时统计)
- 文件版本时间戳(带毫秒级精度)
2. 时间格式转换
enum class TimeZone { local, utc };
enum class TimeFormat { gcode, iso8601Z };
std::string time2str(time_t, TimeZone, TimeFormat); // 时间转字符串
time_t str2time(const std::string&, TimeZone, TimeFormat); // 字符串转时间
- 格式支持:
- G代码格式:
20240315_134500
- ISO8601格式:
2024-03-15T13:45:00Z
- G代码格式:
- 错误处理:
str2time
解析失败返回time_t(-1)
3. 快捷函数
// UTC时间转G代码格式
std::string utc_timestamp();
// UTC时间转ISO8601格式
std::string iso_utc_timestamp();
// 解析ISO8601字符串
time_t parse_iso_utc_timestamp(const std::string&);
关键设计解析
时区处理策略
- 实现要点:
- 使用
gmtime_r
处理UTC - 使用
localtime_r
处理本地时区
- 使用
格式转换示例
格式类型 | 输入时间戳 | 输出示例 |
---|---|---|
GCode | 1647352800 | 20220315_120000 |
ISO8601Z | 1647352800 | 2022-03-15T12:00:00Z |
应用场景
G代码文件头标记
std::string header = "Generated at " + utc_timestamp();
// 输出: GENERATED_AT 20240315_134500
多语言版本管理
std::string filename = "model_" + iso_utc_timestamp() + ".stl";
// 文件名: model_2024-03-15T13:45:00Z.stl
打印耗时统计
time_t start = get_current_milliseconds_time_utc();
print_object();
time_t duration = get_current_milliseconds_time_utc() - start;
关键技术点
跨平台实现
- Windows:使用
GetSystemTimeAsFileTime
- Unix:使用
clock_gettime(CLOCK_REALTIME)
- C++11:备选
std::chrono
实现
错误处理机制
try {
return parse_iso_utc_timestamp(user_input);
} catch (...) {
throw TimeFormatException("Invalid timestamp");
}
性能优化
缓存策略
• 将频繁使用的格式字符串(如G代码时间)预生成
• 使用线程本地存储(TLS)缓存时间结构体
内存管理
• 避免多次内存分配,使用固定大小缓冲区
本模块通过标准化的时间处理方案,确保3D打印流程中各类时间相关操作的一致性与可靠性,为跨时区协作、精确计时需求提供核心支持。