一个基于 C++17 std::chrono 的轻量级跨平台**计时器(Stopwatch)与时间戳(Timestamp)**工具库,附带命令行演示程序。
- Stopwatch(计时器):基于
steady_clock的高精度秒表start/pause/resume/reset,支持暂停后继续累加- 获取纳秒、微秒、毫秒、秒级耗时
- 自动生成人类可读的耗时字符串(如
1.234 s、12.345 ms) - 便捷函数
measure(fn)一次性测量任意函数的执行时间
- Timestamp(时间戳)
- 获取 Unix 秒 / 毫秒 / 微秒时间戳
- 输出 ISO 8601 格式(UTC 与本地时区,可带毫秒)
- 输出
YYYY-MM-DD HH:MM:SS格式与年/月/日/时/分/秒分量
.
├── include/timer/
│ ├── Timer.hpp # 计时器头文件
│ └── Timestamp.hpp # 时间戳头文件
├── src/
│ ├── Timer.cpp # 计时器实现
│ ├── Timestamp.cpp # 时间戳实现
│ └── main.cpp # 演示程序
├── CMakeLists.txt
├── Makefile
└── README.md
cmake -S . -B build
cmake --build build --config Release
./build/timer_timestamp_demo # Linux / macOS
.\build\Release\timer_timestamp_demo.exe # Windows (MSVC)make
make run"C:\Program Files\Microsoft Visual Studio\18\Insiders\VC\Auxiliary\Build\vcvars64.bat"
cl /std:c++17 /EHsc /W4 /Iinclude src\Timer.cpp src\Timestamp.cpp src\main.cpp /Fe:timer_timestamp_demo.exe
timer_timestamp_demo.exe#include "timer/Timer.hpp"
#include "timer/Timestamp.hpp"
using timer::Stopwatch;
using timer::Timestamp;
// 时间戳
const Timestamp now = Timestamp::now();
std::string utc = now.toIsoUtc(); // 2026-08-18T09:30:00.123Z
std::string local = now.toIsoLocal(); // 2026-08-18T17:30:00.123
std::int64_t ms = now.epochMillis(); // 1787093400123
// 计时器
Stopwatch sw;
sw.start();
doSomething();
sw.pause();
double elapsedMs = sw.milliseconds();
std::string text = sw.toString(); // 自动选择合适单位
// 一次性测量
auto d = timer::measure(doSomething); // std::chrono::nanoseconds演示程序输出示例:
========== Timestamp ==========
Now (UTC) : 2026-08-18T09:30:00.123Z
Now (Local) : 2026-08-18T17:30:00.123
...
========== Stopwatch ==========
Loop 50M : 23.456 ms
Sort 5M ints : 512.345 ms
...
- Windows(MSVC / MinGW)
- Linux / macOS(GCC / Clang)
要求 C++17 及以上的编译器。