任务:假设需要做视频编解码显示,需要频繁调用sleep(10ms)函数,如果sleep函数内部误差过大,会导致fps不准确,特别是需要高fps任务。 对比几个方法,测试误差。
#include <iostream>
#include <thread>
#include <chrono>
#include <sys/time.h>
void sleep_for(double ms)
{
// 单位粒度越小,时间越准确,CPU资源占用相对升高
// std::chrono::milliseconds MinSleepDuration(1); //毫秒
std::chrono::microseconds MinSleepDuration(100); //微秒
// std::chrono::nanoseconds MinSleepDuration(100); //纳秒
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
while (std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - start).count() * 1000 < ms)
{
std::this_thread::sleep_for(MinSleepDuration);
}
}
int main()
{
// 模拟100fps
int fps = 0;
std::chrono::milliseconds dura(10); // 10ms
std::chrono::high_resolution_clock::time_point tnow = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 1000; ++i)
{
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
std::chrono::high_resolution_clock::time_point tpost = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::duration<double>>(tpost - tnow).count() * 1000 << std::endl;
tnow = std::chrono::high_resolution_clock::now();
for (int i = 0; i < 1000; ++i)
{
sleep_for(10);
}
tpost = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::duration<double>>(tpost - tnow).count() * 1000 << std::endl;
return 0;
}
|