C++ 高精度微秒级延时函数 (低CPU占用)
在 C++ 中,可以使用 <chrono> 头文件中的高精度时钟来实现微秒级的延时函数。具体实现如下:
#include <chrono>
#include <thread>
void delay_microseconds(int microseconds) {
auto start = std::chrono::high_resolution_clock::now();
while (true) {
auto end = std::chrono::high_resolution_clock::now();
auto elapsed_microseconds = std::chrono::duration_cast<std::chrono::microseconds>(end - start).count();
if (elapsed_microseconds >= microseconds) {
break;
}
std::this_thread::yield();
}
}
该函数使用了一个死循环来等待指定的微秒数,同时使用了 std::this_thread::yield() 函数来放弃 CPU 时间片,以免占用过多 CPU 资源。可以通过调用该函数来实现需要的延时。例如:
// 延时 1000000 微秒
delay_microseconds(1000000);
// 继续执行下一行代码
原文地址: https://www.cveoy.top/t/topic/njAX 著作权归作者所有。请勿转载和采集!