岚天逸见

C++取时间戳窗口

应用场景

防止接口在指定的时间内重复调用,比如 10 秒内不能重复调用。

函数实现

#include <chrono>

/// @brief 计算当前时间戳所属时间窗口的起始点(对齐到 Window 秒的整数倍)
/// @param Window 时间窗口长度(单位:秒)
template <int Window>
int64_t get_windowed_timestamp() {
    const auto now = std::chrono::system_clock::now();
    const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
        now.time_since_epoch()
    ).count();
    return (seconds / Window) * Window;
}

# 测试代码

```c++
#include <iostream>
#include <thread>

int main() {
    for (int i=0; i<100; i++) {
        std::cout << get_windowed_timestamp<10>() << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(2000));
    }

    return 0;
}

posted on 2025-05-14 15:11  岚天逸见  阅读(28)  评论(0)    收藏  举报

导航