Skip to content

Latest commit

 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

cpp-timer-timestamp

一个基于 C++17 std::chrono 的轻量级跨平台**计时器(Stopwatch)时间戳(Timestamp)**工具库,附带命令行演示程序。

功能特性

  • Stopwatch(计时器):基于 steady_clock 的高精度秒表
    • start / pause / resume / reset,支持暂停后继续累加
    • 获取纳秒、微秒、毫秒、秒级耗时
    • 自动生成人类可读的耗时字符串(如 1.234 s12.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

cmake -S . -B build
cmake --build build --config Release
./build/timer_timestamp_demo        # Linux / macOS
.\build\Release\timer_timestamp_demo.exe   # Windows (MSVC)

Makefile(Linux / macOS / MinGW)

make
make run

直接使用 MSVC(Windows)

"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 及以上的编译器。

许可证

MIT License

About

A lightweight C++17 stopwatch and timestamp utility library based on std::chrono

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages