VLink 2.0.0
A high-performance communication middleware
载入中...
搜索中...
未找到
cached_timestamp.h 文件参考

A low-overhead, thread-safe, formatted timestamp generator for log output. 更多...

#include <atomic>
#include <chrono>
#include <cstdint>
#include <mutex>
#include <string_view>
#include "./macros.h"
cached_timestamp.h 的引用(Include)关系图:

浏览该文件的源代码.

 Cached, thread-safe formatted timestamp generator. 更多...

命名空间

详细描述

A low-overhead, thread-safe, formatted timestamp generator for log output.

CachedTimestamp generates a human-readable timestamp string (e.g. "03-18 14:30:01.042") without formatting the full string every call. Instead it caches the date-and-second part and only updates the millisecond field on sub-second increments, significantly reducing the number of expensive strftime / localtime_r calls under high log throughput.

The caching strategy:

  • The full timestamp (up to seconds) is formatted only once per second. The second boundary is detected via an std::atomic<int64_t> storing the last formatted Unix second. Access is serialized so only one thread updates the shared cache at a time.
  • The millisecond field is patched in-place by update_milliseconds() without reformatting the entire string.
  • A std::mutex protects the shared buffer while formatting or patching the millisecond field.
注解
  • The internal buffer is 32 bytes, which is sufficient for most strftime format strings. Using a format that produces a longer string results in truncated output.
  • The default format "%02d-%02d %02d:%02d:%02d.%03d" produces "MM-DD HH:MM:SS.mmm" (18 characters). Do not include year if character count matters.
  • This class is used internally by the VLink Logger. There is normally no need to instantiate it directly in application code.
Example
for (int i = 0; i < 1000; ++i) {
std::string_view sv = ts.get();
write_to_log(sv); // sv points to internal buffer; copy if needed
}