C++实现windows高精度微秒级延时(亲测可用)
代码如下:
#include <iostream>
#include <windows.h>
// 定义一个结构体来保存性能计数器的频率和时间戳
struct PerformanceCounter {
LARGE_INTEGER frequency; // 计数器频率
LARGE_INTEGER start; // 开始时间戳
LARGE_INTEGER end; // 结束时间戳
};
// 初始化性能计数器
void InitPerformanceCounter(PerformanceCounter& counter) {
// 获取计数器频率
QueryPerformanceFrequency(&counter.frequency);
}
// 计算两个时间戳之间的微秒差
double CalculateMicrosecondDifference(const LARGE_INTEGER& start, const LARGE_INTEGER& end, const LARGE_INTEGER& frequency) {
// 计算差值并转换为微秒
return static_cast<double>(end.QuadPart - start.QuadPart) / frequency.QuadPart * 1000000.0;
}
// 实现微秒级延时
void MicrosecondDelay(unsigned int microseconds) {
PerformanceCounter counter;
InitPerformanceCounter(counter);
// 获取延时前的计数器值
QueryPerformanceCounter(&counter.start);
// 计算延时后的计数器目标值
unsigned __int64 targetCounter = counter.start.QuadPart + (static_cast<unsigned __int64>(microseconds) * counter.frequency.QuadPart) / 1000000;
// 循环直到当前计数器值达到或超过目标值
do {
QueryPerformanceCounter(&counter.end);
} while (counter.end.QuadPart < targetCounter);
}
int main() {
// 测试微秒级延时函数5us/次 循环200万次 共10s
std::cout << "开始执行 5 微秒的延时..." << std::endl;
for (int i = 0; i < 2000000; i++)
{
MicrosecondDelay(5);
}
std::cout << "延时结束。" << std::endl;
system("pause");
return 0;
}
标签:windows,counter,C++,LARGE,计数器,QuadPart,INTEGER,微秒,亲测
From: https://blog.csdn.net/weixin_45834799/article/details/137343169