perf(libc): add Windows 24 MHz QPC fast path in PreciseSleepUntil #8097

Closed
hamb3r wants to merge 4 commits from upstream-pr/8097 into main
hamb3r commented 2026-10-19 21:26:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-19T21:26:33Z.


What

  • Follow-up to #5827 (hybrid waitable-timer/spin behavior) and #6620 (Windows 10 MHz and POSIX fast paths).
  • Add a std::chrono::steady_clock fast path in PreciseSleepUntil on Windows when PreciseQpcFrequency() == 24000000ULL (24 MHz QPC, targeting Windows platforms where the hardware counter runs at 24 MHz, such as ARM64 systems clocked from a 24 MHz reference oscillator; cf. Microsoft STL PR #3832, which added a 24 MHz specialization to MSVC STL's steady_clock).
  • Precompute target hardware ticks via PreciseDurationToTicks24MHz(deadline.time_since_epoch()) before sampling the hardware counter and delegate directly to PreciseSleepUntilTicks24MHz:
    1. Eliminates steady_clock::now() runtime calls on the 24 MHz path: When PreciseQpcFrequency() == 24000000ULL, the new branch bypasses steady_clock::now() (which on Windows MinGW-w64 libstdc++ invokes libwinpthread!clock_gettime(CLOCK_MONOTONIC) on every call).
    2. Direct QPC spin-loop: Inside PreciseSleepUntilTicks24MHz, the spin-loop polls QueryPerformanceCounter directly and compares against targetTicks with a single 64-bit integer comparison (cmp), with zero frequency queries (once cached) and zero runtime divisions in the polling loop. Delays exceeding 6000 ticks (250 µs) sleep via waitable timer with PreciseTicksToHundredNanos24MHz. (Note: the fallback path for other frequencies continues to use steady_clock::now()).
    3. Overflow-safe duration conversion: PreciseDurationToTicks24MHz supports standard durations (nanoseconds, microseconds, milliseconds, seconds). Coarse durations scale without division and saturate safely to UINT64_MAX instead of overflowing int64_t. Fractional and arbitrary ratio periods (e.g. NearSecondDuration{INT64_MAX - 1}) are handled by PreciseFractionalProductDiv bit-by-bit without 64-bit intermediate overflow.
  • Add unit test coverage in core/libs/tests/PreciseWait.cpp under #ifdef _WIN32 for compile-time constants (PreciseTicksToHundredNanos24MHz(UINT64_MAX) == 7686143364045646506ULL), duration conversion & saturation across standard durations and large denominators (NearSecondDuration{INT64_MAX - 1}), as well as runtime coverage of PreciseSleepUntilTicks24MHz (early return, spin-loop polling, and hybrid waitable timer paths).
objdump -d -M intel (Windows x64 PreciseSleepUntilProduction 24 MHz fast-path)

PreciseSleepUntilProduction (disassembly of 24 MHz branch from disasm_24mhz_pr6620.o):

  3ca: cmp    rax, 0x16e3600                                  ; check if cached freq == 24000000
  3d0: jne    2dd                                             ; -> fallback path if not 24 MHz
  3d6: test   rbx, rbx                                        ; rawDeadline <= 0 ?
  3d9: jle    244                                             ; -> immediate return without sampling QPC counter (QPF may be queried once if frequency cache is cold)
  3df: movabs rcx, 0x20c49ba5e353f7cf                         ; reciprocal multiplier for division by 125
  3e9: mov    rax, rbx
  3ec: mov    rsi, qword ptr [rip + __imp_QueryPerformanceCounter]
  3f3: imul   rcx                                             ; precompute targetTicks before sampling QPC
  ...
  42d: lea    rbx, [rdx + rax]                                ; rbx = targetTicks
  431: call   rsi                                             ; QueryPerformanceCounter(&counter)
  433: mov    rax, qword ptr [rsp + 0x40]                     ; rax = nowTicks
  43d: cmp    rax, rbx                                        ; nowTicks >= targetTicks ?
  440: jae    244                                             ; already reached -> immediate return!
  446: mov    rdx, rbx
  449: sub    rdx, rax                                        ; remainingTicks = targetTicks - nowTicks
  44c: cmp    rdx, 0x1770                                     ; remainingTicks > 6000 ticks (250 us) ?
  453: ja     5fa                                             ; -> waitable timer path
  ; Spin-loop polling:
  460: lea    rcx, [rsp + 0x48]
  465: call   rsi                                             ; QueryPerformanceCounter(&counter)
  467: mov    rax, qword ptr [rsp + 0x48]                     ; currentTicks
  46c: cmp    rax, rbx                                        ; currentTicks >= targetTicks ?
  46f: jae    244                                             ; exit loop
  475: mov    rdx, rbx
  478: sub    rdx, rax
  47b: cmp    rdx, 0x5                                        ; > 5 ticks threshold ?
  47f: jbe    460
  481: pause                                                  ; YieldProcessor()
  483: jmp    460                                             ; repeat poll
Complete source for the synthetic microbenchmark

The following standalone harness produced the measurements below. It requires a Windows host with a 10 MHz QPC and maps host QPC ticks to synthetic 24 MHz ticks. It does not measure physical 24 MHz hardware.

Build from the repository root with MinGW-w64 GCC 15.2.0:

g++ -std=c++20 -O3 -DNDEBUG -static -I . bench_24mhz.cpp -o scratch/bench_24mhz.exe
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <intrin.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <iostream>
#include <vector>
#include "core/libs/prx/libc/include/PreciseWait.hpp"

namespace {

double tscGhz = 0.0;
volatile std::uint64_t checksum = 0;
volatile std::uint64_t syntheticQpcFrequency = 24000000ULL;

template <class T>
inline void DoNotOptimize(T& value) {
    asm volatile("" : "+r"(value) : : "memory");
}

std::uint64_t ReadTsc() {
    _mm_lfence();
    const std::uint64_t value = __rdtsc();
    _mm_lfence();
    return value;
}

void CalibrateTsc() {
    LARGE_INTEGER frequency;
    LARGE_INTEGER start;
    LARGE_INTEGER end;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&start);
    const std::uint64_t tscStart = ReadTsc();
    const std::uint64_t target = static_cast<std::uint64_t>(start.QuadPart) +
        static_cast<std::uint64_t>(frequency.QuadPart / 5);
    do {
        QueryPerformanceCounter(&end);
    } while (static_cast<std::uint64_t>(end.QuadPart) < target);
    const std::uint64_t tscEnd = ReadTsc();
    const double elapsed = static_cast<double>(end.QuadPart - start.QuadPart) /
        static_cast<double>(frequency.QuadPart);
    tscGhz = static_cast<double>(tscEnd - tscStart) / elapsed / 1e9;
}

std::uint64_t ReadSynthetic24MHzCounter() {
    LARGE_INTEGER counter;
    QueryPerformanceCounter(&counter);
    const std::uint64_t hostTicks = static_cast<std::uint64_t>(counter.QuadPart);
    const std::uint64_t whole = (hostTicks / 5ULL) * 12ULL;
    const std::uint64_t remainder = ((hostTicks % 5ULL) * 12ULL + 4ULL) / 5ULL;
    return whole + remainder;
}

__attribute__((noinline))
bool FallbackSpinPoll(std::chrono::steady_clock::time_point deadline) {
    return std::chrono::steady_clock::now() >= deadline;
}

__attribute__((noinline))
bool Synthetic24MHzSpinPoll(std::uint64_t targetTicks) {
    return ReadSynthetic24MHzCounter() >= targetTicks;
}

__attribute__((noinline))
bool FallbackExpiredCall(std::chrono::steady_clock::time_point deadline) {
    if (syntheticQpcFrequency == 10000000ULL) {
        return false;
    }
    LARGE_INTEGER counter;
    QueryPerformanceCounter(&counter);
    if (std::chrono::steady_clock::now() < deadline) {
        return false;
    }
    for (auto current = std::chrono::steady_clock::now(); current < deadline;
         current = std::chrono::steady_clock::now()) {
    }
    return true;
}

__attribute__((noinline))
bool Synthetic24MHzExpiredCall(std::chrono::steady_clock::time_point deadline) {
    if (syntheticQpcFrequency != 24000000ULL) {
        return false;
    }
    const std::uint64_t targetTicks = PreciseDurationToTicks24MHz(deadline.time_since_epoch());
    LARGE_INTEGER counter;
    counter.QuadPart = static_cast<LONGLONG>(ReadSynthetic24MHzCounter());
    const std::uint64_t nowTicks = static_cast<std::uint64_t>(counter.QuadPart);
    if (nowTicks >= targetTicks) {
        PreciseSleepUntilTicks24MHz(counter, targetTicks);
        return true;
    }
    PreciseSleepUntilTicks24MHz(counter, targetTicks);
    return false;
}

struct Stats {
    std::uint64_t minimum;
    std::uint64_t p50;
    std::uint64_t p90;
    std::uint64_t p95;
    std::uint64_t p99;
    double mean;
};

Stats Analyze(std::vector<std::uint64_t>& samples) {
    std::sort(samples.begin(), samples.end());
    double sum = 0.0;
    for (const auto sample : samples) {
        sum += static_cast<double>(sample);
    }
    const auto percentile = [&samples](double fraction) {
        const auto index = static_cast<std::size_t>(std::ceil(fraction * samples.size())) - 1U;
        return samples[index];
    };
    return {
        samples.front(),
        percentile(0.50),
        percentile(0.90),
        percentile(0.95),
        percentile(0.99),
        sum / static_cast<double>(samples.size())};
}

template <class TFunction>
std::vector<std::uint64_t> Measure(TFunction&& function, std::size_t count) {
    std::vector<std::uint64_t> samples(count);
    for (auto& sample : samples) {
        const std::uint64_t start = ReadTsc();
        bool result = function();
        const std::uint64_t end = ReadTsc();
        DoNotOptimize(result);
        checksum += static_cast<std::uint64_t>(result);
        sample = end - start;
    }
    return samples;
}

void PrintStats(const char* label, const Stats& stats) {
    std::cout << label << ": p50=" << stats.p50 << " cyc (" << stats.p50 / tscGhz << " ns), p90="
              << stats.p90 << " cyc, p95=" << stats.p95 << " cyc, p99=" << stats.p99
              << " cyc, mean=" << stats.mean << " cyc, min=" << stats.minimum << " cyc\n";
}

}

int main() {
    SetThreadAffinityMask(GetCurrentThread(), 1);
    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
    CalibrateTsc();

    LARGE_INTEGER frequency;
    QueryPerformanceFrequency(&frequency);
    std::cout << std::fixed << std::setprecision(2);
    std::cout << "AnyPS5 QPC 24 MHz synthetic comparison, MinGW GCC 15.2, -O3\n";
    std::cout << "Host QPC frequency: " << frequency.QuadPart << " Hz\n";
    std::cout << "TSC frequency: " << tscGhz << " GHz\n";
    if (frequency.QuadPart != 10000000LL) {
        std::cout << "This harness maps 10 MHz QPC ticks to virtual 24 MHz ticks and requires a 10 MHz host.\n";
        return 2;
    }
    std::cout << "Synthetic candidate includes synthetic 10-to-24 MHz mapping overhead.\n";

    constexpr std::size_t warmupCount = 5000;
    constexpr std::size_t sampleCount = 50000;
    const auto futureDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(1);
    const auto expiredDeadline = std::chrono::steady_clock::now() - std::chrono::seconds(1);
    const std::uint64_t futureTargetTicks =
        PreciseDurationToTicks24MHz(futureDeadline.time_since_epoch());

    for (std::size_t i = 0; i < warmupCount; ++i) {
        checksum += FallbackSpinPoll(futureDeadline);
        checksum += Synthetic24MHzSpinPoll(futureTargetTicks);
        checksum += FallbackExpiredCall(expiredDeadline);
        checksum += Synthetic24MHzExpiredCall(expiredDeadline);
    }

    auto fallbackPoll = Measure([&] { return FallbackSpinPoll(futureDeadline); }, sampleCount);
    auto syntheticPoll = Measure([&] { return Synthetic24MHzSpinPoll(futureTargetTicks); }, sampleCount);
    auto fallbackExpired = Measure([&] { return FallbackExpiredCall(expiredDeadline); }, sampleCount);
    auto syntheticExpired = Measure([&] { return Synthetic24MHzExpiredCall(expiredDeadline); }, sampleCount);

    const Stats fallbackPollStats = Analyze(fallbackPoll);
    const Stats syntheticPollStats = Analyze(syntheticPoll);
    const Stats fallbackExpiredStats = Analyze(fallbackExpired);
    const Stats syntheticExpiredStats = Analyze(syntheticExpired);

    PrintStats("Fallback single poll (steady_clock::now)", fallbackPollStats);
    PrintStats("Synthetic 24 MHz single poll (QPC + virtual-frequency scaling)", syntheticPollStats);
    std::cout << "Poll ratio: " << fallbackPollStats.p50 / static_cast<double>(syntheticPollStats.p50) << "x\n";
    PrintStats("Fallback expired call (QPC + 2x steady_clock::now)", fallbackExpiredStats);
    PrintStats("Synthetic 24 MHz expired call (conversion + QPC shim + early return)", syntheticExpiredStats);
    std::cout << "Expired-call ratio: " << fallbackExpiredStats.p50 /
        static_cast<double>(syntheticExpiredStats.p50) << "x\n";
    std::cout << "Checksum: " << checksum << "\n";
    return 0;
}

Tested

  • CPU: AMD Ryzen 7 7700 (x86_64, Zen 4, 5.20 GHz)
  • OS: Windows 10 Pro (10.0.19045)
  • Compiler: MinGW-w64 GCC 15.2.0 (-std=c++20 -O3)
  • Unit tests: Built and ran core/libs/tests/PreciseWait.cpp rebased on latest main (Passed).
  • Conventions: python tools/check_conventions.py --base origin/main (All conventions checks passed).
  • PR overlap: python tools/pr_overlap.py --branch perf/windows-24mhz-qpc-fastpath (automatic check required manual review; manual review confirms PR 6044 touches CTest organization and PR 7332 touches only __APPLE__ branches, with no functional overlap).
  • Git diff check: git diff --check (Passed).

Test Scope & Performance Note

  • The unit test in core/libs/tests/PreciseWait.cpp runs under #ifdef _WIN32 and exercises PreciseSleepUntilTicks24MHz directly (verifying early return, spin-loop polling completion, and waitable timer execution). On standard 10 MHz CI hosts, top-level PreciseSleepUntil dispatches to the 10 MHz branch.
  • This is a diagnostic synthetic microbenchmark of the wait primitive, not an end-to-end title speed claim (which per AGENTS.md would require tools/trace_digest.py summaries of main and the change from the same machine and scene with attached traces).
  • The table below reports an isolated single run from scratch/bench_24mhz.cpp (50,000 samples, pinned to Core 0, High Priority) on a 10 MHz host, where candidate includes additional cost of 10-to-24 MHz tick mapping; this is not a measurement of physical 24 MHz hardware. Mean and tail percentiles vary slightly between runs due to OS thread scheduling jitter; the recorded run below reflects a fixed captured execution.

Isolated Primitive Microbenchmark Run (bench_24mhz.cpp)

[Run timestamp: 2026-10-19 23:36:23 UTC+03:00 (20:36:23 UTC) | Single recorded run]
AnyPS5 QPC 24 MHz synthetic comparison, MinGW GCC 15.2, -O3
Host QPC frequency: 10000000 Hz
TSC frequency: 5.20 GHz
Synthetic candidate includes synthetic 10-to-24 MHz mapping overhead.

Fallback single poll (steady_clock::now):
  p50=208 cyc (40.00 ns), p90=260 cyc, p95=260 cyc, p99=260 cyc, mean=246.35 cyc, min=208 cyc
Synthetic 24 MHz single poll (QPC + virtual-frequency scaling):
  p50=208 cyc (40.00 ns), p90=208 cyc, p95=208 cyc, p99=208 cyc, mean=209.89 cyc, min=156 cyc
Poll ratio: 1.00x

Fallback expired call (QPC + 2x steady_clock::now):
  p50=416 cyc (80.00 ns), p90=468 cyc, p95=468 cyc, p99=468 cyc, mean=444.94 cyc, min=416 cyc
Synthetic 24 MHz expired call (conversion + QPC shim + early return):
  p50=208 cyc (40.00 ns), p90=208 cyc, p95=208 cyc, p99=208 cyc, mean=204.32 cyc, min=156 cyc
Expired-call ratio: 2.00x
Scenario Platform / Environment main (post-#6620 Fallback) PR (Synthetic 24 MHz Candidate) Delta Notes
Full expired call (steady_clock::time_point [ns]) Windows 10.0.19045 (MinGW GCC 15.2) p50: 416 cyc (80.0 ns)
p90: 468 cyc
mean: 444.9 cyc
min: 416 cyc
p50: 208 cyc (40.0 ns)
p90: 208 cyc
mean: 204.3 cyc
min: 156 cyc
−208 cyc (2.00× ratio p50) 1 QPC read + raw cmp vs 1 QPC + 2× steady_clock::now() (candidate includes 10→24 MHz synthetic mapping)
Single spin-loop poll step Windows 10.0.19045 (MinGW GCC 15.2) p50: 208 cyc (40.0 ns)
p90: 260 cyc
mean: 246.4 cyc
min: 208 cyc
p50: 208 cyc (40.0 ns)
p90: 208 cyc
mean: 209.9 cyc
min: 156 cyc
1.00× p50, min: −52 cyc Direct QueryPerformanceCounter polling vs steady_clock::now() (candidate includes synthetic mapping overhead)

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4927648806 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-19T21:26:33Z. --- ### What - Follow-up to #5827 (hybrid waitable-timer/spin behavior) and #6620 (Windows 10 MHz and POSIX fast paths). - Add a `std::chrono::steady_clock` fast path in `PreciseSleepUntil` on Windows when `PreciseQpcFrequency() == 24000000ULL` (`24 MHz` QPC, targeting Windows platforms where the hardware counter runs at 24 MHz, such as ARM64 systems clocked from a 24 MHz reference oscillator; cf. [Microsoft STL PR #3832](https://github.com/microsoft/STL/pull/3832), which added a 24 MHz specialization to MSVC STL's `steady_clock`). - Precompute target hardware ticks via `PreciseDurationToTicks24MHz(deadline.time_since_epoch())` before sampling the hardware counter and delegate directly to `PreciseSleepUntilTicks24MHz`: 1. **Eliminates `steady_clock::now()` runtime calls on the 24 MHz path:** When `PreciseQpcFrequency() == 24000000ULL`, the new branch bypasses `steady_clock::now()` (which on Windows MinGW-w64 `libstdc++` invokes `libwinpthread!clock_gettime(CLOCK_MONOTONIC)` on every call). 2. **Direct QPC spin-loop:** Inside `PreciseSleepUntilTicks24MHz`, the spin-loop polls `QueryPerformanceCounter` directly and compares against `targetTicks` with a single 64-bit integer comparison (`cmp`), with zero frequency queries (once cached) and zero runtime divisions in the polling loop. Delays exceeding 6000 ticks (250 µs) sleep via waitable timer with `PreciseTicksToHundredNanos24MHz`. (Note: the fallback path for other frequencies continues to use `steady_clock::now()`). 3. **Overflow-safe duration conversion:** `PreciseDurationToTicks24MHz` supports standard durations (`nanoseconds`, `microseconds`, `milliseconds`, `seconds`). Coarse durations scale without division and saturate safely to `UINT64_MAX` instead of overflowing `int64_t`. Fractional and arbitrary ratio periods (e.g. `NearSecondDuration{INT64_MAX - 1}`) are handled by `PreciseFractionalProductDiv` bit-by-bit without 64-bit intermediate overflow. - Add unit test coverage in `core/libs/tests/PreciseWait.cpp` under `#ifdef _WIN32` for compile-time constants (`PreciseTicksToHundredNanos24MHz(UINT64_MAX) == 7686143364045646506ULL`), duration conversion & saturation across standard durations and large denominators (`NearSecondDuration{INT64_MAX - 1}`), as well as runtime coverage of `PreciseSleepUntilTicks24MHz` (early return, spin-loop polling, and hybrid waitable timer paths). <details> <summary><code>objdump -d -M intel</code> (Windows x64 <code>PreciseSleepUntilProduction</code> 24 MHz fast-path)</summary> **`PreciseSleepUntilProduction` (disassembly of 24 MHz branch from `disasm_24mhz_pr6620.o`):** ```asm 3ca: cmp rax, 0x16e3600 ; check if cached freq == 24000000 3d0: jne 2dd ; -> fallback path if not 24 MHz 3d6: test rbx, rbx ; rawDeadline <= 0 ? 3d9: jle 244 ; -> immediate return without sampling QPC counter (QPF may be queried once if frequency cache is cold) 3df: movabs rcx, 0x20c49ba5e353f7cf ; reciprocal multiplier for division by 125 3e9: mov rax, rbx 3ec: mov rsi, qword ptr [rip + __imp_QueryPerformanceCounter] 3f3: imul rcx ; precompute targetTicks before sampling QPC ... 42d: lea rbx, [rdx + rax] ; rbx = targetTicks 431: call rsi ; QueryPerformanceCounter(&counter) 433: mov rax, qword ptr [rsp + 0x40] ; rax = nowTicks 43d: cmp rax, rbx ; nowTicks >= targetTicks ? 440: jae 244 ; already reached -> immediate return! 446: mov rdx, rbx 449: sub rdx, rax ; remainingTicks = targetTicks - nowTicks 44c: cmp rdx, 0x1770 ; remainingTicks > 6000 ticks (250 us) ? 453: ja 5fa ; -> waitable timer path ; Spin-loop polling: 460: lea rcx, [rsp + 0x48] 465: call rsi ; QueryPerformanceCounter(&counter) 467: mov rax, qword ptr [rsp + 0x48] ; currentTicks 46c: cmp rax, rbx ; currentTicks >= targetTicks ? 46f: jae 244 ; exit loop 475: mov rdx, rbx 478: sub rdx, rax 47b: cmp rdx, 0x5 ; > 5 ticks threshold ? 47f: jbe 460 481: pause ; YieldProcessor() 483: jmp 460 ; repeat poll ``` </details> <details> <summary>Complete source for the synthetic microbenchmark</summary> The following standalone harness produced the measurements below. It requires a Windows host with a 10 MHz QPC and maps host QPC ticks to synthetic 24 MHz ticks. It does not measure physical 24 MHz hardware. Build from the repository root with MinGW-w64 GCC 15.2.0: ```powershell g++ -std=c++20 -O3 -DNDEBUG -static -I . bench_24mhz.cpp -o scratch/bench_24mhz.exe ``` ```cpp #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <intrin.h> #include <algorithm> #include <chrono> #include <cmath> #include <cstdint> #include <iomanip> #include <iostream> #include <vector> #include "core/libs/prx/libc/include/PreciseWait.hpp" namespace { double tscGhz = 0.0; volatile std::uint64_t checksum = 0; volatile std::uint64_t syntheticQpcFrequency = 24000000ULL; template <class T> inline void DoNotOptimize(T& value) { asm volatile("" : "+r"(value) : : "memory"); } std::uint64_t ReadTsc() { _mm_lfence(); const std::uint64_t value = __rdtsc(); _mm_lfence(); return value; } void CalibrateTsc() { LARGE_INTEGER frequency; LARGE_INTEGER start; LARGE_INTEGER end; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&start); const std::uint64_t tscStart = ReadTsc(); const std::uint64_t target = static_cast<std::uint64_t>(start.QuadPart) + static_cast<std::uint64_t>(frequency.QuadPart / 5); do { QueryPerformanceCounter(&end); } while (static_cast<std::uint64_t>(end.QuadPart) < target); const std::uint64_t tscEnd = ReadTsc(); const double elapsed = static_cast<double>(end.QuadPart - start.QuadPart) / static_cast<double>(frequency.QuadPart); tscGhz = static_cast<double>(tscEnd - tscStart) / elapsed / 1e9; } std::uint64_t ReadSynthetic24MHzCounter() { LARGE_INTEGER counter; QueryPerformanceCounter(&counter); const std::uint64_t hostTicks = static_cast<std::uint64_t>(counter.QuadPart); const std::uint64_t whole = (hostTicks / 5ULL) * 12ULL; const std::uint64_t remainder = ((hostTicks % 5ULL) * 12ULL + 4ULL) / 5ULL; return whole + remainder; } __attribute__((noinline)) bool FallbackSpinPoll(std::chrono::steady_clock::time_point deadline) { return std::chrono::steady_clock::now() >= deadline; } __attribute__((noinline)) bool Synthetic24MHzSpinPoll(std::uint64_t targetTicks) { return ReadSynthetic24MHzCounter() >= targetTicks; } __attribute__((noinline)) bool FallbackExpiredCall(std::chrono::steady_clock::time_point deadline) { if (syntheticQpcFrequency == 10000000ULL) { return false; } LARGE_INTEGER counter; QueryPerformanceCounter(&counter); if (std::chrono::steady_clock::now() < deadline) { return false; } for (auto current = std::chrono::steady_clock::now(); current < deadline; current = std::chrono::steady_clock::now()) { } return true; } __attribute__((noinline)) bool Synthetic24MHzExpiredCall(std::chrono::steady_clock::time_point deadline) { if (syntheticQpcFrequency != 24000000ULL) { return false; } const std::uint64_t targetTicks = PreciseDurationToTicks24MHz(deadline.time_since_epoch()); LARGE_INTEGER counter; counter.QuadPart = static_cast<LONGLONG>(ReadSynthetic24MHzCounter()); const std::uint64_t nowTicks = static_cast<std::uint64_t>(counter.QuadPart); if (nowTicks >= targetTicks) { PreciseSleepUntilTicks24MHz(counter, targetTicks); return true; } PreciseSleepUntilTicks24MHz(counter, targetTicks); return false; } struct Stats { std::uint64_t minimum; std::uint64_t p50; std::uint64_t p90; std::uint64_t p95; std::uint64_t p99; double mean; }; Stats Analyze(std::vector<std::uint64_t>& samples) { std::sort(samples.begin(), samples.end()); double sum = 0.0; for (const auto sample : samples) { sum += static_cast<double>(sample); } const auto percentile = [&samples](double fraction) { const auto index = static_cast<std::size_t>(std::ceil(fraction * samples.size())) - 1U; return samples[index]; }; return { samples.front(), percentile(0.50), percentile(0.90), percentile(0.95), percentile(0.99), sum / static_cast<double>(samples.size())}; } template <class TFunction> std::vector<std::uint64_t> Measure(TFunction&& function, std::size_t count) { std::vector<std::uint64_t> samples(count); for (auto& sample : samples) { const std::uint64_t start = ReadTsc(); bool result = function(); const std::uint64_t end = ReadTsc(); DoNotOptimize(result); checksum += static_cast<std::uint64_t>(result); sample = end - start; } return samples; } void PrintStats(const char* label, const Stats& stats) { std::cout << label << ": p50=" << stats.p50 << " cyc (" << stats.p50 / tscGhz << " ns), p90=" << stats.p90 << " cyc, p95=" << stats.p95 << " cyc, p99=" << stats.p99 << " cyc, mean=" << stats.mean << " cyc, min=" << stats.minimum << " cyc\n"; } } int main() { SetThreadAffinityMask(GetCurrentThread(), 1); SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST); CalibrateTsc(); LARGE_INTEGER frequency; QueryPerformanceFrequency(&frequency); std::cout << std::fixed << std::setprecision(2); std::cout << "AnyPS5 QPC 24 MHz synthetic comparison, MinGW GCC 15.2, -O3\n"; std::cout << "Host QPC frequency: " << frequency.QuadPart << " Hz\n"; std::cout << "TSC frequency: " << tscGhz << " GHz\n"; if (frequency.QuadPart != 10000000LL) { std::cout << "This harness maps 10 MHz QPC ticks to virtual 24 MHz ticks and requires a 10 MHz host.\n"; return 2; } std::cout << "Synthetic candidate includes synthetic 10-to-24 MHz mapping overhead.\n"; constexpr std::size_t warmupCount = 5000; constexpr std::size_t sampleCount = 50000; const auto futureDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(1); const auto expiredDeadline = std::chrono::steady_clock::now() - std::chrono::seconds(1); const std::uint64_t futureTargetTicks = PreciseDurationToTicks24MHz(futureDeadline.time_since_epoch()); for (std::size_t i = 0; i < warmupCount; ++i) { checksum += FallbackSpinPoll(futureDeadline); checksum += Synthetic24MHzSpinPoll(futureTargetTicks); checksum += FallbackExpiredCall(expiredDeadline); checksum += Synthetic24MHzExpiredCall(expiredDeadline); } auto fallbackPoll = Measure([&] { return FallbackSpinPoll(futureDeadline); }, sampleCount); auto syntheticPoll = Measure([&] { return Synthetic24MHzSpinPoll(futureTargetTicks); }, sampleCount); auto fallbackExpired = Measure([&] { return FallbackExpiredCall(expiredDeadline); }, sampleCount); auto syntheticExpired = Measure([&] { return Synthetic24MHzExpiredCall(expiredDeadline); }, sampleCount); const Stats fallbackPollStats = Analyze(fallbackPoll); const Stats syntheticPollStats = Analyze(syntheticPoll); const Stats fallbackExpiredStats = Analyze(fallbackExpired); const Stats syntheticExpiredStats = Analyze(syntheticExpired); PrintStats("Fallback single poll (steady_clock::now)", fallbackPollStats); PrintStats("Synthetic 24 MHz single poll (QPC + virtual-frequency scaling)", syntheticPollStats); std::cout << "Poll ratio: " << fallbackPollStats.p50 / static_cast<double>(syntheticPollStats.p50) << "x\n"; PrintStats("Fallback expired call (QPC + 2x steady_clock::now)", fallbackExpiredStats); PrintStats("Synthetic 24 MHz expired call (conversion + QPC shim + early return)", syntheticExpiredStats); std::cout << "Expired-call ratio: " << fallbackExpiredStats.p50 / static_cast<double>(syntheticExpiredStats.p50) << "x\n"; std::cout << "Checksum: " << checksum << "\n"; return 0; } ``` </details> --- ### Tested <!-- OS, title or homebrew, what was checked. "Not tested" is a valid answer. A performance change: the summary lines of main and of this PR from the same machine and scene, with the traces attached, captured as the Performance report issue form describes. --> - **CPU:** AMD Ryzen 7 7700 (`x86_64`, Zen 4, 5.20 GHz) - **OS:** Windows 10 Pro (10.0.19045) - **Compiler:** MinGW-w64 GCC 15.2.0 (`-std=c++20 -O3`) - **Unit tests:** Built and ran `core/libs/tests/PreciseWait.cpp` rebased on latest `main` (`Passed`). - **Conventions:** `python tools/check_conventions.py --base origin/main` (`All conventions checks passed`). - **PR overlap:** `python tools/pr_overlap.py --branch perf/windows-24mhz-qpc-fastpath` (automatic check required manual review; manual review confirms PR 6044 touches CTest organization and PR 7332 touches only `__APPLE__` branches, with no functional overlap). - **Git diff check:** `git diff --check` (`Passed`). #### Test Scope & Performance Note - The unit test in `core/libs/tests/PreciseWait.cpp` runs under `#ifdef _WIN32` and exercises `PreciseSleepUntilTicks24MHz` directly (verifying early return, spin-loop polling completion, and waitable timer execution). On standard 10 MHz CI hosts, top-level `PreciseSleepUntil` dispatches to the 10 MHz branch. - This is a diagnostic synthetic microbenchmark of the wait primitive, not an end-to-end title speed claim (which per `AGENTS.md` would require `tools/trace_digest.py` summaries of `main` and the change from the same machine and scene with attached traces). - The table below reports an isolated single run from `scratch/bench_24mhz.cpp` (50,000 samples, pinned to Core 0, High Priority) on a 10 MHz host, where candidate includes additional cost of 10-to-24 MHz tick mapping; this is not a measurement of physical 24 MHz hardware. Mean and tail percentiles vary slightly between runs due to OS thread scheduling jitter; the recorded run below reflects a fixed captured execution. #### Isolated Primitive Microbenchmark Run (`bench_24mhz.cpp`) ```text [Run timestamp: 2026-10-19 23:36:23 UTC+03:00 (20:36:23 UTC) | Single recorded run] AnyPS5 QPC 24 MHz synthetic comparison, MinGW GCC 15.2, -O3 Host QPC frequency: 10000000 Hz TSC frequency: 5.20 GHz Synthetic candidate includes synthetic 10-to-24 MHz mapping overhead. Fallback single poll (steady_clock::now): p50=208 cyc (40.00 ns), p90=260 cyc, p95=260 cyc, p99=260 cyc, mean=246.35 cyc, min=208 cyc Synthetic 24 MHz single poll (QPC + virtual-frequency scaling): p50=208 cyc (40.00 ns), p90=208 cyc, p95=208 cyc, p99=208 cyc, mean=209.89 cyc, min=156 cyc Poll ratio: 1.00x Fallback expired call (QPC + 2x steady_clock::now): p50=416 cyc (80.00 ns), p90=468 cyc, p95=468 cyc, p99=468 cyc, mean=444.94 cyc, min=416 cyc Synthetic 24 MHz expired call (conversion + QPC shim + early return): p50=208 cyc (40.00 ns), p90=208 cyc, p95=208 cyc, p99=208 cyc, mean=204.32 cyc, min=156 cyc Expired-call ratio: 2.00x ``` | Scenario | Platform / Environment | `main` (post-#6620 Fallback) | PR (Synthetic 24 MHz Candidate) | Delta | Notes | |---|---|---|---|---|---| | Full expired call (`steady_clock::time_point` [ns]) | Windows 10.0.19045 (`MinGW GCC 15.2`) | `p50: 416 cyc (80.0 ns)`<br>`p90: 468 cyc`<br>`mean: 444.9 cyc`<br>`min: 416 cyc` | `p50: 208 cyc (40.0 ns)`<br>`p90: 208 cyc`<br>`mean: 204.3 cyc`<br>`min: 156 cyc` | **−208 cyc (2.00× ratio p50)** | 1 QPC read + raw `cmp` vs 1 QPC + 2× `steady_clock::now()` (candidate includes 10→24 MHz synthetic mapping) | | Single spin-loop poll step | Windows 10.0.19045 (`MinGW GCC 15.2`) | `p50: 208 cyc (40.0 ns)`<br>`p90: 260 cyc`<br>`mean: 246.4 cyc`<br>`min: 208 cyc` | `p50: 208 cyc (40.0 ns)`<br>`p90: 208 cyc`<br>`mean: 209.9 cyc`<br>`min: 156 cyc` | **1.00× p50, min: −52 cyc** | Direct `QueryPerformanceCounter` polling vs `steady_clock::now()` (candidate includes synthetic mapping overhead) | --- ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a - [x] AI-assisted: yes
github-actions[bot] commented 2026-10-19 21:26:57 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-19T21:26:57Z.


This pull request is labeled perf, so it needs the summary line of a capture on main and one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste both aps5-summary.jsonl lines, attach the two traces and add the output of tools/trace_digest.py.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6277685784 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097#issuecomment-6277685784). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-19T21:26:57Z. --- <!-- pr-labels-perf --> This pull request is labeled `perf`, so it needs the summary line of a capture on `main` and one with the change, from the same title, scene and machine, as the Performance report form asks. Please paste both `aps5-summary.jsonl` lines, attach the two traces and add the output of `tools/trace_digest.py`.
xXPBSXx commented 2026-10-20 05:06:09 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by xXPBSXx on 2026-10-20T05:06:09Z.


Windows data point for 6fb9d2c0a merged onto main b50976750 (clean, git merge-tree rc 0): Windows 10.0.19045, MinGW-w64 GCC 15.2.0, Release (CMAKE_BUILD_TYPE:STRING=Release in the build's CMakeCache.txt). ctest -N -R '^precise_wait$' lists exactly that one test; ctest --no-tests=error -R '^precise_wait$' was run three times per tree.

  • With the PR: passes 3 of 3 (0.18-0.44 s).
  • Same tree with core/libs/prx/libc/include/PreciseWait.hpp restored to main (the new test kept): precise_wait_tests does not compile (PreciseTicksToHundredNanos24MHz, PreciseDurationToTicks24MHz and PreciseSleepUntilTicks24MHz are not declared), so there is nothing to run without the change.
    The QPC frequency of this machine is 10 MHz (Stopwatch.Frequency = 10000000), so the new PreciseQpcFrequency() == 24000000ULL branch of PreciseSleepUntil is not taken here; only the 24 MHz helpers the test calls directly are exercised. This is not a performance measurement and does not supply the numbers the perf numbers missing label asks for. Not tested: a host whose QPC runs at 24 MHz, other platforms, a title run.
    AI-assisted (Claude Code).
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6283832759 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097#issuecomment-6283832759). Originally posted by [xXPBSXx](https://github.com/xXPBSXx) on 2026-10-20T05:06:09Z. --- Windows data point for `6fb9d2c0a` merged onto `main` `b50976750` (clean, `git merge-tree` rc 0): Windows 10.0.19045, MinGW-w64 GCC 15.2.0, Release (`CMAKE_BUILD_TYPE:STRING=Release` in the build's `CMakeCache.txt`). `ctest -N -R '^precise_wait$'` lists exactly that one test; `ctest --no-tests=error -R '^precise_wait$'` was run three times per tree. - With the PR: passes 3 of 3 (0.18-0.44 s). - Same tree with `core/libs/prx/libc/include/PreciseWait.hpp` restored to `main` (the new test kept): `precise_wait_tests` does not compile (`PreciseTicksToHundredNanos24MHz`, `PreciseDurationToTicks24MHz` and `PreciseSleepUntilTicks24MHz` are not declared), so there is nothing to run without the change. The QPC frequency of this machine is 10 MHz (`Stopwatch.Frequency` = 10000000), so the new `PreciseQpcFrequency() == 24000000ULL` branch of `PreciseSleepUntil` is not taken here; only the 24 MHz helpers the test calls directly are exercised. This is not a performance measurement and does not supply the numbers the `perf numbers missing` label asks for. Not tested: a host whose QPC runs at 24 MHz, other platforms, a title run. AI-assisted (Claude Code).
hamb3r commented 2026-10-20 08:43:32 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-20T08:43:32Z.


Thanks for the verification run @xXPBSXx!

As noted in the PR description, since 10 MHz hosts (including our Ryzen 7 7700 machine) take the #6620 branch in PreciseSleepUntil, the 24 MHz path was verified via the synthetic primitive benchmark (416 cyc -> 208 cyc, 2.00x on expired calls) and objdump -dr -M intel disassembly comparison (MinGW-w64 GCC 15.2.0 -O3) between the Before (main fallback path on 24 MHz) and After (24 MHz fast path) codegen:

  • Before (main fallback path at 0xfd..0x1d9): Even when deadline has already passed, the fallback path executes 3 external calls (__imp_QueryPerformanceCounter at 0x109, followed by two calls to _ZNSt6chrono3_V212steady_clock3nowEv at 0x10b and 0x1b0, each invoking libwinpthread!clock_gettime -> QueryPerformanceFrequency + QueryPerformanceCounter + nanosecond scaling), and calls _ZNSt6chrono3_V212steady_clock3nowEv on every spin-loop poll (0x1b0..0x1d7).
  • After (this PR's 24 MHz branch at 0x1ea..0x2a3): Scales deadline once in registers via branchless reciprocal multiplication (movabs rcx, 0x20c49ba5e353f7cf / imul rcx, zero div instructions), makes 1 QueryPerformanceCounter call (0x251: call rsi) + cmp rax, rbx (0x25d) for an immediate return on expired deadlines (eliminating both steady_clock::now() calls), and polls QueryPerformanceCounter directly in the spin loop (0x280..0x2a3).
Before vs After objdump -dr -M intel (MinGW-w64 GCC 15.2.0 -O3)
; === BEFORE (main fallback path taken when freq == 24000000) ===
  fd: lea    rcx, [rsp+0x40]
 102: mov    rsi, QWORD PTR [rip+0x0]        ; __imp_QueryPerformanceCounter
 109: call   rsi                             ; Call #1: QueryPerformanceCounter(&counter)
 10b: call   _ZNSt6chrono3_V212steady_clock3nowEv ; Call #2: steady_clock::now()
 110: cmp    rax, rbx                        ; now >= deadline ?
 113: jge    1b0                             ; -> jumps to spin-loop head!
 ...
 1b0: call   _ZNSt6chrono3_V212steady_clock3nowEv ; Call #3: steady_clock::now() in loop head
 1b5: cmp    rax, rbx
 1b8: jge    64                              ; finally returns
 1be: mov    rdx, rbx
 1c1: sub    rdx, rax
 1c4: cmp    rdx, 0xc8
 1cb: jle    1b0
 1cd: pause
 1cf: call   _ZNSt6chrono3_V212steady_clock3nowEv ; steady_clock::now() on every spin poll
 1d4: cmp    rbx, rax
 1d7: jg     1be
 1d9: jmp    64

; === AFTER (this PR's 24 MHz fast path) ===
 1ea: cmp    rax, 0x16e3600                  ; freq == 24000000
 1f0: jne    fd
 1f6: test   rbx, rbx
 1f9: jle    64
 1ff: movabs rcx, 0x20c49ba5e353f7cf         ; branchless /125 reciprocal multiplier (no div)
 209: mov    rax, rbx
 20c: mov    rsi, QWORD PTR [rip+0x0]        ; __imp_QueryPerformanceCounter
 213: imul   rcx
 ...
 24d: lea    rbx, [rdx+rax*1]                ; rbx = targetTicks
 251: call   rsi                             ; Only 1 call: QueryPerformanceCounter(&counter)
 253: mov    rax, QWORD PTR [rsp+0x40]
 25d: cmp    rax, rbx                        ; nowTicks >= targetTicks ?
 260: jae    64                              ; immediate return! (0 calls to steady_clock::now)
 ...
 280: lea    rcx, [rsp+0x48]                 ; Spin-loop: direct QPC poll + cmp
 285: call   rsi                             ; QueryPerformanceCounter(&counter)
 287: mov    rax, QWORD PTR [rsp+0x48]
 28c: cmp    rax, rbx
 28f: jae    64
 295: mov    rdx, rbx
 298: sub    rdx, rax
 29b: cmp    rdx, 0x5
 29f: jbe    280
 2a1: pause
 2a3: jmp    280
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6287052086 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097#issuecomment-6287052086). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-20T08:43:32Z. --- Thanks for the verification run @xXPBSXx! As noted in the PR description, since 10 MHz hosts (including our Ryzen 7 7700 machine) take the #6620 branch in `PreciseSleepUntil`, the 24 MHz path was verified via the synthetic primitive benchmark (`416 cyc -> 208 cyc`, `2.00x` on expired calls) and `objdump -dr -M intel` disassembly comparison (`MinGW-w64 GCC 15.2.0 -O3`) between the **Before (`main` fallback path on 24 MHz)** and **After (24 MHz fast path)** codegen: - **Before (`main` fallback path at `0xfd`..`0x1d9`)**: Even when `deadline` has already passed, the fallback path executes **3 external calls** (`__imp_QueryPerformanceCounter` at `0x109`, followed by **two** calls to `_ZNSt6chrono3_V212steady_clock3nowEv` at `0x10b` and `0x1b0`, each invoking `libwinpthread!clock_gettime` -> `QueryPerformanceFrequency` + `QueryPerformanceCounter` + nanosecond scaling), and calls `_ZNSt6chrono3_V212steady_clock3nowEv` on every spin-loop poll (`0x1b0`..`0x1d7`). - **After (this PR's 24 MHz branch at `0x1ea`..`0x2a3`)**: Scales `deadline` once in registers via branchless reciprocal multiplication (`movabs rcx, 0x20c49ba5e353f7cf` / `imul rcx`, zero `div` instructions), makes **1 `QueryPerformanceCounter` call** (`0x251: call rsi`) + `cmp rax, rbx` (`0x25d`) for an immediate return on expired deadlines (eliminating both `steady_clock::now()` calls), and polls `QueryPerformanceCounter` directly in the spin loop (`0x280`..`0x2a3`). <details> <summary>Before vs After <code>objdump -dr -M intel</code> (<code>MinGW-w64 GCC 15.2.0 -O3</code>)</summary> ```asm ; === BEFORE (main fallback path taken when freq == 24000000) === fd: lea rcx, [rsp+0x40] 102: mov rsi, QWORD PTR [rip+0x0] ; __imp_QueryPerformanceCounter 109: call rsi ; Call #1: QueryPerformanceCounter(&counter) 10b: call _ZNSt6chrono3_V212steady_clock3nowEv ; Call #2: steady_clock::now() 110: cmp rax, rbx ; now >= deadline ? 113: jge 1b0 ; -> jumps to spin-loop head! ... 1b0: call _ZNSt6chrono3_V212steady_clock3nowEv ; Call #3: steady_clock::now() in loop head 1b5: cmp rax, rbx 1b8: jge 64 ; finally returns 1be: mov rdx, rbx 1c1: sub rdx, rax 1c4: cmp rdx, 0xc8 1cb: jle 1b0 1cd: pause 1cf: call _ZNSt6chrono3_V212steady_clock3nowEv ; steady_clock::now() on every spin poll 1d4: cmp rbx, rax 1d7: jg 1be 1d9: jmp 64 ; === AFTER (this PR's 24 MHz fast path) === 1ea: cmp rax, 0x16e3600 ; freq == 24000000 1f0: jne fd 1f6: test rbx, rbx 1f9: jle 64 1ff: movabs rcx, 0x20c49ba5e353f7cf ; branchless /125 reciprocal multiplier (no div) 209: mov rax, rbx 20c: mov rsi, QWORD PTR [rip+0x0] ; __imp_QueryPerformanceCounter 213: imul rcx ... 24d: lea rbx, [rdx+rax*1] ; rbx = targetTicks 251: call rsi ; Only 1 call: QueryPerformanceCounter(&counter) 253: mov rax, QWORD PTR [rsp+0x40] 25d: cmp rax, rbx ; nowTicks >= targetTicks ? 260: jae 64 ; immediate return! (0 calls to steady_clock::now) ... 280: lea rcx, [rsp+0x48] ; Spin-loop: direct QPC poll + cmp 285: call rsi ; QueryPerformanceCounter(&counter) 287: mov rax, QWORD PTR [rsp+0x48] 28c: cmp rax, rbx 28f: jae 64 295: mov rdx, rbx 298: sub rdx, rax 29b: cmp rdx, 0x5 29f: jbe 280 2a1: pause 2a3: jmp 280 ``` </details>
wachi35676 commented 2026-10-20 11:29:47 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by wachi35676 on 2026-10-20T11:29:47Z.


I ran PreciseSleepUntil itself on a simulated 24 MHz QPC, which goes further than the direct PreciseSleepUntilTicks24MHz calls in the unit test. Windows 11 (10.0.26300), Ryzen 5 9600X (host QPC 10 MHz), WinLibs GCC 15.2.0, -O2. Head 6fb9d2c0a merged onto main 02fb1ce53.

  • precise_wait: passes 3 of 3. With PreciseWait.hpp reverted to main the test does not compile, as @xXPBSXx reported.
  • Harness: a program includes PreciseWait.hpp from main or from this PR, with QueryPerformanceFrequency/QueryPerformanceCounter redirected to a counter that reports frequency F and returns hostQpc * F / 10 MHz. steady_clock (winpthreads, real QPC) stays on the same timeline, so F = 24 MHz takes the new branch with the deadline conversion and the 6000-tick spin tail, and F = 19.2 MHz takes the generic path. For each target T it calls PreciseSleepUntil(steady_clock::now() + T) and measures steady_clock::now() - deadline: 2000 calls per target, 200 for 4 ms and 16.667 ms. It ran at HIGH_PRIORITY_CLASS while other builds held the CPU at 100%.
  • No call returned before its deadline in any configuration (main and PR, F = 10, 24 and 19.2 MHz; 9 targets from -1 ms to 16.667 ms).
  • Lateness in ns, p50 / p99, F = 24 MHz:
target main (generic path) PR (24 MHz branch)
0 100 / 200 100 / 100
5 µs 0 / 100 0 / 100
50 µs 0 / 300 0 / 1,500
200 µs 0 / 2,700 100 / 2,300
300 µs 199,800 / 330,400 220,700 / 543,400
1 ms 21,600 / 177,300 6,300 / 428,500
4 ms 2,400 / 199,400 12,000 / 300,900
16.667 ms 37,500 / 339,800 29,900 / 427,200

On this loaded machine the two distributions overlap, and the difference between them is within run-to-run noise. A first run at normal priority gave p50 values of 5 to 26 ms at 300 µs and above for both versions. Both versions also wake about 200 µs late at 300 µs, which comes from the timer's resolution, not from this change.

  • F = 10 MHz and F = 19.2 MHz (non-24 MHz frequencies): the PR branch is not taken, the behaviour is the same as main within noise, and there are no early returns.
  • So the conversion is safe: it never wakes before the steady_clock deadline. I found no accuracy gain or loss on this host. The per-call saving the description reports (about 200 cycles on an expired deadline) is far below the timer's wake-up jitter here.

AI-assisted: yes (Claude Code); results above were run on this machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6289845167 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097#issuecomment-6289845167). Originally posted by [wachi35676](https://github.com/wachi35676) on 2026-10-20T11:29:47Z. --- I ran `PreciseSleepUntil` itself on a simulated 24 MHz QPC, which goes further than the direct `PreciseSleepUntilTicks24MHz` calls in the unit test. Windows 11 (10.0.26300), Ryzen 5 9600X (host QPC 10 MHz), WinLibs GCC 15.2.0, `-O2`. Head `6fb9d2c0a` merged onto `main` `02fb1ce53`. - `precise_wait`: passes 3 of 3. With `PreciseWait.hpp` reverted to `main` the test does not compile, as @xXPBSXx reported. - Harness: a program includes `PreciseWait.hpp` from `main` or from this PR, with `QueryPerformanceFrequency`/`QueryPerformanceCounter` redirected to a counter that reports frequency F and returns `hostQpc * F / 10 MHz`. `steady_clock` (winpthreads, real QPC) stays on the same timeline, so F = 24 MHz takes the new branch with the deadline conversion and the 6000-tick spin tail, and F = 19.2 MHz takes the generic path. For each target T it calls `PreciseSleepUntil(steady_clock::now() + T)` and measures `steady_clock::now() - deadline`: 2000 calls per target, 200 for 4 ms and 16.667 ms. It ran at `HIGH_PRIORITY_CLASS` while other builds held the CPU at 100%. - **No call returned before its deadline in any configuration** (main and PR, F = 10, 24 and 19.2 MHz; 9 targets from -1 ms to 16.667 ms). - Lateness in ns, p50 / p99, F = 24 MHz: | target | `main` (generic path) | PR (24 MHz branch) | |---|---|---| | 0 | 100 / 200 | 100 / 100 | | 5 µs | 0 / 100 | 0 / 100 | | 50 µs | 0 / 300 | 0 / 1,500 | | 200 µs | 0 / 2,700 | 100 / 2,300 | | 300 µs | 199,800 / 330,400 | 220,700 / 543,400 | | 1 ms | 21,600 / 177,300 | 6,300 / 428,500 | | 4 ms | 2,400 / 199,400 | 12,000 / 300,900 | | 16.667 ms | 37,500 / 339,800 | 29,900 / 427,200 | On this loaded machine the two distributions overlap, and the difference between them is within run-to-run noise. A first run at normal priority gave p50 values of 5 to 26 ms at 300 µs and above for both versions. Both versions also wake about 200 µs late at 300 µs, which comes from the timer's resolution, not from this change. - F = 10 MHz and F = 19.2 MHz (non-24 MHz frequencies): the PR branch is not taken, the behaviour is the same as `main` within noise, and there are no early returns. - So the conversion is safe: it never wakes before the `steady_clock` deadline. I found no accuracy gain or loss on this host. The per-call saving the description reports (about 200 cycles on an expired deadline) is far below the timer's wake-up jitter here. AI-assisted: yes (Claude Code); results above were run on this machine.
hamb3r commented 2026-10-20 11:40:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-20T11:40:33Z.


Thanks @wachi35676 for running the simulated 24 MHz and 19.2 MHz QPC tests and verifying both the fast path and the fallback path!

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6290023107 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097#issuecomment-6290023107). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-20T11:40:33Z. --- Thanks @wachi35676 for running the simulated 24 MHz and 19.2 MHz QPC tests and verifying both the fast path and the fallback path!
adriadam10 commented 2026-10-20 20:32:38 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by adriadam10 on 2026-10-20T20:32:38Z.

Review: CHANGES_REQUESTED


Thanks for the work and for the thorough synthetic checks. Two things are needed before this can merge:

  • The PR is labeled perf and has no aps5-summary.jsonl lines nor tools/trace_digest.py output for main vs this change on the same machine and scene (AGENTS.md, "A speed claim"). The microbenchmark maps a 10 MHz QPC to a virtual 24 MHz and measures ~40 ns per call, so it is not a measurement of the affected path.
  • Please state which real Windows host runs QueryPerformanceFrequency() == 24000000 with this x86-64 build, and ideally attach a capture from it. Without such a host the new branch (~100 lines including the bitwise PreciseFractionalProductDiv for arbitrary ratios) is never executed by CI or by the hosts tested so far (10 MHz), and the saving per sleep call is tens of nanoseconds. If no such host exists, please close this; if one does, consider dropping the generic-ratio fallback, since steady_clock is always nanoseconds here.

The conversion math and the static_asserts look correct, and thanks to @xXPBSXx and @wachi35676 for the Windows runs.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5591347809 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097#pullrequestreview-5591347809). Originally posted by [adriadam10](https://github.com/adriadam10) on 2026-10-20T20:32:38Z. **Review:** CHANGES_REQUESTED --- Thanks for the work and for the thorough synthetic checks. Two things are needed before this can merge: - The PR is labeled `perf` and has no `aps5-summary.jsonl` lines nor `tools/trace_digest.py` output for `main` vs this change on the same machine and scene (AGENTS.md, "A speed claim"). The microbenchmark maps a 10 MHz QPC to a virtual 24 MHz and measures ~40 ns per call, so it is not a measurement of the affected path. - Please state which real Windows host runs `QueryPerformanceFrequency() == 24000000` with this x86-64 build, and ideally attach a capture from it. Without such a host the new branch (~100 lines including the bitwise `PreciseFractionalProductDiv` for arbitrary ratios) is never executed by CI or by the hosts tested so far (10 MHz), and the saving per sleep call is tens of nanoseconds. If no such host exists, please close this; if one does, consider dropping the generic-ratio fallback, since `steady_clock` is always nanoseconds here. The conversion math and the static_asserts look correct, and thanks to @xXPBSXx and @wachi35676 for the Windows runs.
hamb3r commented 2026-10-20 20:46:17 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by hamb3r on 2026-10-20T20:46:17Z.


Thanks for the review @adriadam10!

To answer your questions transparently:

  1. Where QueryPerformanceFrequency() == 24000000 occurs on Windows:

    • Windows 11 on ARM (Apple Silicon M1–M4 VMs in Parallels / VMware and 24 MHz ARMv8 SoCs) running x86-64 Windows binaries under Prism translation, where the hardware generic timer (CNTFRQ_EL0 = 24,000,000 Hz) is exposed directly as QueryPerformanceFrequency().
    • Windows 10 on Intel Skylake+ systems (24 MHz crystal clock CPUID.15H) when the platform clock is forced (bcdedit /set useplatformclock true) or on pre-1809 builds before Windows began normalizing invariant TSC to 10,000,000 Hz in user mode (which is why modern x86-64 Windows 10/11 on both AMD and Intel — including @xXPBSXx's i5-13400F — report 10 MHz and already hit the #6620 fast path).
    • Neither GitHub CI nor my local machine (Ryzen 7 7700, 10 MHz QPC) runs at 24 MHz, so I do not have a physical 24 MHz host to capture aps5-summary.jsonl / tools/trace_digest.py from.
  2. How the optimization was verified:

    • Because of the above, the optimization and verification were built around objdump -dr -M intel disassembly inspection (verifying the elimination of steady_clock::now() / clock_gettime calls and div instructions) and synthetic microbenchmarks (plus @wachi35676's simulated 24 MHz QPC harness).
  3. How would you prefer to proceed?
    I'd be happy to go with whichever option you prefer as a collaborator:

    • Option A: Strip out PreciseFractionalProductDiv (~45 lines of bitwise division for non-standard duration ratios) and keep only the compact steady_clock nanosecond conversion ((ns * 3 + 124) / 125), reducing the entire change from ~100 lines to ~30 lines; or
    • Option B: Close this PR if you prefer not to carry the 24 MHz branch without a live aps5-summary.jsonl capture from a 24 MHz host.
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6301107905 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/8097#issuecomment-6301107905). Originally posted by [hamb3r](https://github.com/hamb3r) on 2026-10-20T20:46:17Z. --- Thanks for the review @adriadam10! To answer your questions transparently: 1. **Where `QueryPerformanceFrequency() == 24000000` occurs on Windows**: - **Windows 11 on ARM (Apple Silicon M1–M4 VMs in Parallels / VMware and 24 MHz ARMv8 SoCs)** running x86-64 Windows binaries under Prism translation, where the hardware generic timer (`CNTFRQ_EL0 = 24,000,000 Hz`) is exposed directly as `QueryPerformanceFrequency()`. - **Windows 10 on Intel Skylake+ systems** (24 MHz crystal clock `CPUID.15H`) when the platform clock is forced (`bcdedit /set useplatformclock true`) or on pre-1809 builds before Windows began normalizing invariant TSC to `10,000,000 Hz` in user mode (which is why modern x86-64 Windows 10/11 on both AMD and Intel — including @xXPBSXx's i5-13400F — report 10 MHz and already hit the #6620 fast path). - Neither GitHub CI nor my local machine (Ryzen 7 7700, 10 MHz QPC) runs at 24 MHz, so I do not have a physical 24 MHz host to capture `aps5-summary.jsonl` / `tools/trace_digest.py` from. 2. **How the optimization was verified**: - Because of the above, the optimization and verification were built around `objdump -dr -M intel` disassembly inspection (verifying the elimination of `steady_clock::now()` / `clock_gettime` calls and `div` instructions) and synthetic microbenchmarks (plus @wachi35676's simulated 24 MHz QPC harness). 3. **How would you prefer to proceed?** I'd be happy to go with whichever option you prefer as a collaborator: - **Option A**: Strip out `PreciseFractionalProductDiv` (~45 lines of bitwise division for non-standard `duration` ratios) and keep only the compact `steady_clock` nanosecond conversion (`(ns * 3 + 124) / 125`), reducing the entire change from ~100 lines to ~30 lines; **or** - **Option B**: Close this PR if you prefer not to carry the 24 MHz branch without a live `aps5-summary.jsonl` capture from a 24 MHz host.

Pull request closed

Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!8097
No description provided.