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;
        
        // 精确延时500ms
        auto 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;
}

 运行结果如下:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌武贰玖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值