帧率控制
test_sleep_fps.cpp
#include <iostream>
#include <ctime>
#include <thread>
#include <Windows.h>
using namespace std;
void MySleep(int ms)
{
auto beg = clock();
for (int i = 0; i < ms; i++)
{
this_thread::sleep_for(1ms);
if ((clock() - beg) / (CLOCKS_PER_SEC / 1000) >= ms)
{
break;
}
}
}
int main()
{
auto beg = clock();// 开始时间 cpu 跳数
int fps = 0;
// 测试 c++11 的 sleep
// 测试 sleep 10ms 100fps
for (;;)
{
fps++;
this_thread::sleep_for(10ms);
// CLOCKS_PER_SEC 为 cpu 每秒经过的跳数
if ((clock() - beg) / (CLOCKS_PER_SEC / 1000) >= 1000)
{
cout << "sleep_for fps = " << fps << endl;
break;
}
}
//测试wait 事件超时控制 帧率
auto handle = CreateEvent(NULL, FALSE, FALSE, NULL);
beg = clock();
fps = 0;
for (;;)
{
fps++;
WaitForSingleObject(handle, 10);// 等待超时
if ((clock() - beg) / (CLOCKS_PER_SEC / 1000) >= 1000)
{
cout << "wait fps = " << fps << endl;
break;
}
}
beg = clock();
fps = 0;
for (;;)
{
fps++;
MySleep(10);
if ((clock() - beg) / (CLOCKS_PER_SEC / 1000) >= 1000)
{
cout << "MySleep fps = " << fps << endl;
break;
}
}
getchar();
return 0;
}
测试结果
测试后的帧率距离100相差的比较多。