C++實現(xiàn)精確延時的多種方法與性能對比
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) {
// 提高系統(tǒng)定時器精度(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. 忙等待實現(xiàn) (最高精度但最耗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框架實現(xiàn)
#include <QElapsedTimer>
#include <QThread>
void qtPreciseDelay(int milliseconds) {
QElapsedTimer timer;
timer.start();
while (timer.elapsed() < milliseconds) {
QThread::usleep(100); // 減少CPU占用
}
}精度比較表
| 方法 | 精度 | CPU占用 | 跨平臺 | 備注 |
|---|---|---|---|---|
| <chrono> + sleep | 1-5ms | 低 | 是 | 推薦通用方案 |
| Windows API | <1ms | 中 | 否 | Windows最佳方案 |
| nanosleep | <1ms | 低 | Linux/Unix | Linux最佳方案 |
| 忙等待 | <0.1ms | 100% | 是 | 僅用于極短延時 |
| Qt實現(xiàn) | 1-5ms | 低 | 是 | Qt項目適用 |
使用建議
通用場景:使用C++11 <chrono> 庫實現(xiàn),兼顧精度和可移植性
Windows高精度:使用 QueryPerformanceCounter + timeBeginPeriod
實時性要求高:考慮RTOS或?qū)S糜布〞r器
避免忙等待:長時間延時應(yīng)結(jié)合sleep以減少CPU占用
示例:精確500ms延時循環(huán)
#include <iostream>
#include <chrono>
#include <thread>
int main() {
for (int i = 0; i < 10; i++) {
auto start = std::chrono::high_resolution_clock::now();
// 你的任務(wù)代碼
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;
}運行結(jié)果如下:

選擇哪種方法取決于你的具體需求、目標平臺和精度要求。
到此這篇關(guān)于C++實現(xiàn)精確延時的多種方法與性能對比的文章就介紹到這了,更多相關(guān)C++延時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一篇文章讓你輕松理解C++中vector和list區(qū)別
對于學c語言的同學來說,vector和list這兩個東西經(jīng)常會搞錯,下面這篇文章主要給大家介紹了關(guān)于C++中vector和list區(qū)別的相關(guān)資料,需要的朋友可以參考下2022-01-01
C語言中獲取和改變目錄的相關(guān)函數(shù)總結(jié)
這篇文章主要介紹了C語言中獲取和改變目錄的相關(guān)函數(shù)總結(jié),包括getcwd()函數(shù)和chdir()函數(shù)以及chroot()函數(shù)的使用方法,需要的朋友可以參考下2015-09-09
c++ STL容器總結(jié)之:vertor與list的應(yīng)用
本篇文章對c++中STL容器中的vertor與list的應(yīng)用進行了詳細的分析解釋。需要的朋友參考下2013-05-05
使用c語言輕松實現(xiàn)動態(tài)內(nèi)存管
這篇文章主要介紹了使用c語言輕松實現(xiàn)動態(tài)內(nèi)存管,本文章內(nèi)容詳細,具有很好的參考價值,希望對大家有所幫助,需要的朋友可以參考下2023-01-01

