当前位置: 首页 > news >正文

C++实现精确延时的方法

在C++中实现精确延时有多种方法,以下是几种常见的实现方式,适用于不同场景和精度要求:

1. 标准库方法

<chrono> 高精度延时 (推荐)

#include <chrono>
#include <thread>void preciseDelay(int milliseconds) {auto start = std::chrono::high_resolution_clock::now();while (true) {auto now = std::chrono::high_resolution_clock::now();auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();if (elapsed >= milliseconds) {break;}std::this_thread::sleep_for(std::chrono::microseconds(100)); // 减少CPU占用}
}

2. Windows平台专用方法

高精度定时器 (Windows API)

#include <windows.h>void preciseDelayWin(int milliseconds) {// 提高系统定时器精度(1ms)TIMECAPS tc;timeGetDevCaps(&tc, sizeof(TIMECAPS));timeBeginPeriod(tc.wPeriodMin);LARGE_INTEGER frequency;LARGE_INTEGER start;LARGE_INTEGER end;QueryPerformanceFrequency(&frequency);QueryPerformanceCounter(&start);do {QueryPerformanceCounter(&end);} while ((end.QuadPart - start.QuadPart) * 1000 / frequency.QuadPart < milliseconds);timeEndPeriod(tc.wPeriodMin);
}

3. Linux平台专用方法

nanosleep 高精度延时

#include <time.h>void preciseDelayLinux(int milliseconds) {struct timespec ts;ts.tv_sec = milliseconds / 1000;ts.tv_nsec = (milliseconds % 1000) * 1000000;int res;do {res = nanosleep(&ts, &ts);} while (res != 0);
}

4. 忙等待实现 (最高精度但最耗CPU)

#include <chrono>void busyWaitDelay(int milliseconds) {auto start = std::chrono::high_resolution_clock::now();while (true) {auto now = std::chrono::high_resolution_clock::now();auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now - start).count();if (elapsed >= milliseconds) {break;}}
}

 5. Qt框架实现 

#include <QElapsedTimer>
#include <QThread>void qtPreciseDelay(int milliseconds) {QElapsedTimer timer;timer.start();while (timer.elapsed() < milliseconds) {QThread::usleep(100); // 减少CPU占用}
}

精度比较表

方法精度CPU占用跨平台备注
<chrono> + sleep1-5ms推荐通用方案
Windows API<1msWindows最佳方案
nanosleep<1msLinux/UnixLinux最佳方案
忙等待<0.1ms100%仅用于极短延时
Qt实现1-5msQt项目适用

使用建议

  1. 通用场景:使用C++11 <chrono> 库实现,兼顾精度和可移植性

  2. Windows高精度:使用 QueryPerformanceCounter + timeBeginPeriod

  3. 实时性要求高:考虑RTOS或专用硬件定时器

  4. 避免忙等待:长时间延时应结合sleep以减少CPU占用

示例:精确500ms延时循环

#include <iostream>
#include <chrono>
#include <thread>int main() {for (int i = 0; i < 10; i++) {auto start = std::chrono::high_resolution_clock::now();// 你的任务代码std::cout << "Task " << i << " executed at " << std::chrono::system_clock::now().time_since_epoch().count() << " ns" << std::endl;// 精确延时500msauto end = std::chrono::high_resolution_clock::now();auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();if (elapsed < 500) {std::this_thread::sleep_for(std::chrono::milliseconds(500 - elapsed));}}return 0;
}

 运行结果如下:

选择哪种方法取决于你的具体需求、目标平台和精度要求。

http://www.dtcms.com/a/296940.html

相关文章:

  • 季逸超:Manus的上下文工程启示
  • Photoshop下载安装入门教程:从下载安装到第一次完美使用
  • 应急响应】Linux 自用应急响应工具发版 v6.0(LinuxGun)
  • 20 BTLO 蓝队靶场 Sticky Situation 解题记录
  • Voice AI Agent 知识库:打造你自己的语音智能体!
  • Vitest 用法详解及 Coverage Web 工具介绍
  • C# 密封类_密封方法 (seadled 关键字)
  • 【postgresql按照逗号分割字段,并统计数量和求和】
  • 【Spring AI 1.0.0】Spring AI 1.0.0框架快速入门(4)——Chat Memory(聊天记录)
  • SpringCloud【Sentinel】
  • 7.3.2 内核内存管理运行机制
  • 到底可不可以用jion?jion如何优化?
  • MapStruct类型转换接口未自动注入到spring容器中
  • Web前端:JavaScript find()函数内判断
  • Redis 单线程模型与多线程机制
  • kettle 8.2 ETL项目【二、加载数据】
  • 「Linux命令基础」用户和用户组实训
  • rust-方法语法
  • 背包DP之分组背包
  • mac电脑(m1) - flask断点失效
  • Datawhale AI数据分析 作业2
  • 力扣1287:有序数组中出现次数超过25%的元素
  • Linux join命令快速从大文件中匹配内容
  • 构建 Odoo 18 移动端导航:深入解析 OWL 框架、操作与服务
  • P1013 [NOIP 1998 提高组] 进制位
  • 【算法】递归、搜索与回溯算法入门
  • 星痕共鸣数据分析2
  • 【Guava】1.1.我的报告
  • 移动前端开发与 Web 前端开发的区别
  • 电商接口常见误区与踩坑提醒