首页 > 后端开发 > C++ > 正文

C++怎么实现一个计时器(Timer)_C++多线程与高精度时间测量

穿越時空
发布: 2025-11-24 09:45:36
原创
883人浏览过
使用std::chrono和std::thread可实现高精度跨平台计时器,支持单次与周期性任务。1. 通过steady_clock测量时间间隔;2. 结合sleep_until实现延时执行;3. 封装Timer类管理线程安全的定时任务;4. 多定时任务宜用优先队列统一调度以提升效率。

c++怎么实现一个计时器(timer)_c++多线程与高精度时间测量

在C++中实现一个计时器(Timer),尤其是结合多线程和高精度时间测量时,需要使用现代C++标准库中的 std::chronostd::thread。这种方式不仅跨平台,而且能提供微秒甚至纳秒级的精度。

1. 使用 std::chrono 实现高精度时间测量

C++11 引入了 std::chrono,它提供了对时间点(time_point)、时间段(duration)和时钟(clock)的封装,适合做高精度计时。

常用时钟类型:

  • std::chrono::steady_clock:单调递增,不受系统时间调整影响,推荐用于计时。
  • std::chrono::high_resolution_clock:最高精度时钟,通常就是 steady_clock 的别名。

示例:测量代码执行时间

立即学习C++免费学习笔记(深入)”;

#include <iostream>
#include <chrono>
<p>int main() {
auto start = std::chrono::steady_clock::now();</p><pre class='brush:php;toolbar:false;'>// 模拟耗时操作
for (int i = 0; i < 1000000; ++i) {
    // do nothing
}

auto end = std::chrono::steady_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end - start);

std::cout << "耗时: " << duration.count() << " 微秒\n";
return 0;
登录后复制

}

2. 实现单次/周期性定时任务(Timer)

可以利用 std::threadstd::this_thread::sleep_until 来实现一个简单的定时器。

目标:在指定时间后执行函数,或周期性执行。

抖云猫AI论文助手
抖云猫AI论文助手

一款AI论文写作工具,最快 2 分钟,生成 3.5 万字论文。论文可插入表格、代码、公式、图表,依托自研学术抖云猫大模型,生成论文具备严谨的学术专业性。

抖云猫AI论文助手 146
查看详情 抖云猫AI论文助手
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
<p>void simple_timer(int delay_ms, std::function<void()> task) {
auto wake_time = std::chrono::steady_clock::now() +
std::chrono::milliseconds(delay_ms);
std::this_thread::sleep_until(wake_time);
task();
}</p><p>// 周期性执行
void periodic_timer(int interval_ms, int times, std::function<void()> task) {
for (int i = 0; i < times; ++i) {
auto next_time = std::chrono::steady_clock::now() +
std::chrono::milliseconds(interval_ms);
task();
std::this_thread::sleep_until(next_time);
}
}</p>
登录后复制

调用示例:

int main() {
    simple_timer(1000, []() {
        std::cout << "1秒后执行\n";
    });
<pre class='brush:php;toolbar:false;'>periodic_timer(500, 3, []() {
    std::cout << "周期任务执行\n";
});

return 0;
登录后复制

}

3. 多线程安全的 Timer 类设计

如果要支持多个定时任务并行运行,应将每个定时器放在独立线程中,避免阻塞主线程。

class Timer {
public:
    Timer() : running(false) {}
<pre class='brush:php;toolbar:false;'>~Timer() {
    stop();
}

void start_once(int delay_ms, std::function<void()> task) {
    stop();
    running = true;
    thread = std::thread([=]() {
        auto target = std::chrono::steady_clock::now() +
                      std::chrono::milliseconds(delay_ms);
        std::this_thread::sleep_until(target);
        if (running) task();
    });
}

void start_periodic(int interval_ms, std::function<void()> task) {
    stop();
    running = true;
    thread = std::thread([=]() {
        while (running) {
            auto next_time = std::chrono::steady_clock::now() +
                             std::chrono::milliseconds(interval_ms);
            task();
            std::this_thread::sleep_until(next_time);
        }
    });
}

void stop() {
    running = false;
    if (thread.joinable()) {
        thread.join();
    }
}
登录后复制

private: std::thread thread; bool running; };

使用方式:

int main() {
    Timer timer;
    timer.start_once(1000, []() {
        std::cout << "一次性任务\n";
    });
<pre class='brush:php;toolbar:false;'>std::this_thread::sleep_for(std::chrono::seconds(2));

timer.start_periodic(300, []() {
    std::cout << "每300ms执行一次\n";
});

std::this_thread::sleep_for(std::chrono::seconds(2));
return 0;
登录后复制

}

4. 注意事项与优化建议

  • 优先使用 std::chrono::steady_clock,避免系统时间跳变影响计时。
  • sleep_until 虽然高精度,但实际精度受限于操作系统的调度粒度(通常为1-15ms)。
  • 频繁短间隔定时任务可能因线程调度延迟而无法精确执行,考虑使用事件循环或定时器轮询机制(如基于 epoll 或 IOCP)提升效率。
  • 若需大量定时器,可使用 std::priority_queue 管理超时任务,配合一个工作线程统一调度。

基本上就这些。C++ 中实现 Timer 不复杂,关键是选对时钟和线程控制方式。

以上就是C++怎么实现一个计时器(Timer)_C++多线程与高精度时间测量的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号