Developer knowledge network · moderated exchange

مجتمع الكود غير الموثوق به

أبحاث المطورين، مجتمع الهندسة العكسية والترميز

Knowledge indexيعيش
4Categories
919Threads
2.8Kدعامات
Guide

High-Precision Frame Limiter using QueryPerformanceCounter in C++

imgui_artisan
UI Designer
MEMBER
مندوب: 202
تاريخ الانضمام: Apr 2019
دعامات: 54
شكرًا: 28
3 weeks ago · Jul 27, 2026 2:14 PM
#1

Standard Sleep(1) in Win32 has a resolution of 1-15ms which causes jittery 144Hz overlay rendering.

Hybrid Precision Frame Limiter:

CPP
void LimitFrameRate(double targetFps) {
    static LARGE_INTEGER freq, lastTime;
    static bool init = false;
    if (!init) { QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&lastTime); init = true; }
    
    double targetDelta = 1.0 / targetFps;
    LARGE_INTEGER currentTime;
    QueryPerformanceCounter(&currentTime);
    
    double elapsed = (double)(currentTime.QuadPart - lastTime.QuadPart) / freq.QuadPart;
    while (elapsed < targetDelta) {
        if (targetDelta - elapsed > 0.002) {
            Sleep(1); // Coarse sleep to yield CPU
        } else {
            YieldProcessor(); // Fine spinwait for last 2ms
        }
        QueryPerformanceCounter(&currentTime);
        elapsed = (double)(currentTime.QuadPart - lastTime.QuadPart) / freq.QuadPart;
    }
    lastTime = currentTime;
}

Delivers rock-solid 144.00 FPS with 0.05ms frame-time variance!

matrix_math_guy
Math Specialist
MEMBER
مندوب: 105
تاريخ الانضمام: Aug 2018
دعامات: 52
شكرًا: 41
3 weeks ago · Jul 27, 2026 4:32 PM
#2

The hybrid Sleep(1) + YieldProcessor() approach keeps CPU usage at 0.5% while delivering sub-millisecond frame pacing.

dx12_render_dev
DX12 Master
MEMBER
مندوب: 55
تاريخ الانضمام: Oct 2020
دعامات: 9
شكرًا: 65
3 weeks ago · Jul 28, 2026 12:59 AM
#3

Frame time graph in ImGui is a flat horizontal line with this.