fix(libkernel): read Windows thread CPU clocks from thread cycle time #23238

Merged
videogamer10293 merged 1 commit from upstream-pr/23238 into main 2026-11-18 23:51:00 +00:00
videogamer10293 commented 2026-11-18 20:45:54 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by videogamer10293 on 2026-11-18T20:45:54Z.


What

On Windows, the thread CPU clocks came from GetThreadTimes: clock_gettime with clock 14, and the clock pthread_getcpuclockid gives for a guest thread. Those times advance in 15.62 ms steps, also with the timer resolution raised to 0.5 ms, while clock_getres reports 1 µs for these clocks. They can also read ahead of wall time, by up to 6.45 ms in the probe below.

With an invariant TSC (CPUID 0x80000007 EDX bit 8), both clocks now read QueryThreadCycleTime and divide it by the host TSC frequency that libkernel already measures for sceKernelGetTscFrequency (HostTscFrequency_nid_no_patch). Microsoft writes "Do not attempt to convert the CPU clock cycles returned by QueryThreadCycleTime to elapsed time" and documents no time unit, so the numbers below compare the result with wall time. Without an invariant TSC the clocks stay on GetThreadTimes.

Unchanged: clocks 1 and 2 and getrusage report user and system time apart. A cycle count cannot split them. Clock 15 is a process-wide total, and #18471 changes it separately; its diff and this one touch different lines. The first read now measures the TSC frequency if nothing did before: that pins the calling thread to one CPU and waits 20 ms.

The new debt entry records what is measured and what is not. The fragment fix-nkwebkit-cputime.md from merged #20139, not folded yet, said its clock comes from GetThreadTimes on Windows; this PR updates that text in place, since debt_fold.py cannot change an entry that is still pending.

Test. guest_thread_cpu_clock gets ThreadClocksAdvanceInSmallSteps. A thread burns 200 ms of its own CPU time, with a short busy loop between readings of its clock, once through clock 14 and once through its pthread_getcpuclockid clock. Readings must not go back. The clock may not advance more than the monotonic clock plus 2% and 2 ms, nor less than the process CPU clock (clock 2) minus 10% and 31.25 ms. At least 100 readings must differ; a clock that moves in 15.62 ms steps gives about 13. A Windows host without an invariant TSC skips that last check, since the clock keeps the steps there.

Tested

Windows 10 Pro 10.0.19045, AMD Ryzen 5 7600X (invariant TSC bit set), NVIDIA GeForce RTX 5070 Ti for the GPU tests, WinLibs GCC 15.2.0 r7, Release. Tested on main 2a9d82dbf6 with the branch at 6abac1715f. This PR's commit differs from it only in the debt entry's wording and a rebase onto newer main, whose new commits change none of this PR's files; the tests were not run again after that. Both trees carry the same uncommitted _putenv_s guard in UploadCacheReadOnlyFlush.cpp, without which main does not build on Windows (#19899, #22373 and #22634 fix it).

  • Through libkernel (libclock.cpp below), clock 14 on one thread for 1 s of wall time, 20 fresh processes per row. "Reads" does nothing but read the clock. "Work" spends 3.9 µs per step on a busy loop and two other system calls, and reads the clock once per millisecond.

    build loop distinct readings per second clock 14 against wall time
    main reads 64 0.000% in all 20
    branch reads 8583540 to 8656730 -5.87% to -5.67%
    main work 64 0.000% in all 20
    branch work 1000 to 1001 -0.21% to -0.03%

    HostTscFrequency_nid_no_patch ranged from 4691035024 to 4691079935 Hz over these and the loaded starts. With 12 busy threads running, the "work" thread gave most of its time away; main's clock 14 did not move once in 20 runs, and the branch's gave 84 to 127 readings.

  • What the "reads" loop loses. Without any AnyPS5 library (probe4.cpp), a thread's cycle time divided by the TSC frequency stayed within 0.03% of wall time with no system calls (within 0.25% over the five saved runs of this probe). With about 10 million QueryThreadCycleTime calls a second it read 6.50% low, about 6.5 ns per call; SwitchToThread, WaitForSingleObject and GetThreadTimes lost 1 ns or less per call. So the clock seems to leave part of each of its own reads uncounted; the debt entry records this.

  • GetThreadTimes without AnyPS5 (probe.cpp, 40 runs per row): a thread burns until GetThreadTimes has advanced by more than 0.1 s. Its largest step was 15.62 ms in all five rows: no load, 12 and 24 busy threads at the default timer resolution, and no load and 12 busy threads at 0.5 ms. In 5 of the 200 runs it got there before 0.1 s of wall time had passed, by up to 6.45 ms. The thread's QueryThreadCycleTime never read ahead.

  • The new check. guest_thread_cpu_clock passed on the branch 5 of 5 alone and 20 of 20 with 12 busy threads running. The branch's test executable with main's libraries aborted 5 of 5; main's own test executable passed 5 of 5 with the same libraries (exit code 0).

  • Mutations, each built and run 3 times: each failed the test 3 of 3: clock 14 read with GetThreadTimes again, a guest thread's clock read with GetThreadTimes again, the converted time doubled, the converted time halved, the conversion's remainder term dropped, and the invariant TSC check made to report none. The unchanged branch passed 3 of 3 before and after.

  • tools/select_tests.py selected the same 5400 tests on both sides, run with -j 8; 26 were skipped on both. Both sides failed agc_driver_stencil_plane_memory (#22427), agc_driver_msaa_dcc_unwatch, agc_driver_bda_device (#22773) and nkwebkit_wtfcputime. main also failed frame_capture_minimize and the branch agc_driver_image_table_packed_guards. Run again 5 times alone and 5 times with 12 busy threads on each side, those two failed once each on main and never on the branch.

  • nkwebkit_wtfcputime reads clock 14. It passed 20 of 20 alone on each side. With 12 busy threads it failed 8 of 20 on main and 13 of 20 on the branch; two earlier rounds of 20 on main 6286d36449 gave 7 on main and 9 on f0828c0734, then 11 on main and 8 on b218c883c6. Every failure was at line 111, which checks that the main thread's own CPU time stays under 30 ms. With the precise clock on the branch, this suggests the thread really used more than 30 ms under load; why was not examined here.

Not tested: Linux and macOS, whose clock code is unchanged but where the new check also runs; Intel CPUs; a CPU without an invariant TSC; titles. tools/pr_overlap.py could not compare 12 open PRs that conflict with main; their diffs were compared by hand and none touches the changed functions.

libclock.cpp (g++ -O2 -std=c++20 -static)
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <string>
#include <thread>

struct Timespec {
    std::int64_t sec;
    std::int64_t nsec;
};

using ClockGettime = int(__attribute__((sysv_abi)) *)(int, Timespec*);
using TscFrequency = std::uint64_t(__attribute__((sysv_abi)) *)();

static double WallSeconds() {
    LARGE_INTEGER frequency, now;
    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&now);
    return static_cast<double>(now.QuadPart) / static_cast<double>(frequency.QuadPart);
}

int main(int argc, char** argv) {
    const double burnSeconds = argc > 1 ? std::atof(argv[1]) : 1.0;
    const bool work = argc > 2 && std::string(argv[2]) == "work";
    const HANDLE event = CreateEventW(nullptr, TRUE, TRUE, nullptr);
    const HMODULE kernel = LoadLibraryA("libkernel.prx");
    if (kernel == nullptr) {
        std::printf("LoadLibrary libkernel.prx failed %lu\n", GetLastError());
        return 2;
    }
    const auto clockGettime = reinterpret_cast<ClockGettime>(GetProcAddress(kernel, "clock_gettime_nid_postfix"));
    const auto tscFrequency = reinterpret_cast<TscFrequency>(GetProcAddress(kernel, "HostTscFrequency_nid_no_patch"));
    if (clockGettime == nullptr || tscFrequency == nullptr) return 3;
    const std::uint64_t frequency = tscFrequency();
    double cpu = 0;
    double wall = 0;
    int steps = 0;
    long long workSteps = 0;
    std::thread([&] {
        Timespec start{}, now{};
        clockGettime(14, &start);
        const double wallStart = WallSeconds();
        std::int64_t previous = start.sec * 1000000000LL + start.nsec;
        double nextRead = 0;
        while (WallSeconds() - wallStart < burnSeconds) {
            if (work) {
                volatile unsigned x = 0;
                for (int i = 0; i < 20000; ++i) x = x + i;
                WaitForSingleObject(event, 0);
                SwitchToThread();
                ++workSteps;
                if (WallSeconds() - wallStart < nextRead) continue;
                nextRead += 0.001;
            }
            clockGettime(14, &now);
            const std::int64_t value = now.sec * 1000000000LL + now.nsec;
            if (value != previous) ++steps;
            previous = value;
        }
        clockGettime(14, &now);
        wall = WallSeconds() - wallStart;
        cpu = static_cast<double>((now.sec - start.sec) * 1000000000LL + (now.nsec - start.nsec)) / 1e9;
    }).join();
    std::printf("%s: HostTscFrequency %llu Hz; clock 14 over a %.3f s burn: %.4f s, %+.3f ms against wall (%+.3f %%), %d distinct readings, %.2f us per work step\n",
                work ? "work" : "reads", static_cast<unsigned long long>(frequency), wall, cpu, (cpu - wall) * 1e3, (cpu - wall) / wall * 100.0, steps, workSteps ? wall * 1e6 / static_cast<double>(workSteps) : 0.0);
    return 0;
}
probe.cpp (probe_res.cpp adds NtSetTimerResolution(5000))
#include <windows.h>
#include <intrin.h>
#include <atomic>
#include <chrono>
#include <cstdio>
#include <thread>
#include <vector>
#include <algorithm>
static double ThreadTimesSeconds() {
    FILETIME c, e, k, u;
    GetThreadTimes(GetCurrentThread(), &c, &e, &k, &u);
    auto t = [](FILETIME f) { return (static_cast<unsigned long long>(f.dwHighDateTime) << 32) | f.dwLowDateTime; };
    return (t(k) + t(u)) * 100e-9;
}
static double tscHz = 0;
static double CycleSeconds() {
    ULONG64 cycles = 0;
    QueryThreadCycleTime(GetCurrentThread(), &cycles);
    return cycles / tscHz;
}
int main(int argc, char** argv) {
    const int load = argc > 1 ? atoi(argv[1]) : 0;
    LARGE_INTEGER f, a, b;
    QueryPerformanceFrequency(&f);
    QueryPerformanceCounter(&a);
    auto t0 = __rdtsc();
    Sleep(200);
    QueryPerformanceCounter(&b);
    auto t1 = __rdtsc();
    tscHz = (t1 - t0) / (double(b.QuadPart - a.QuadPart) / f.QuadPart);
    std::atomic<bool> stop{false};
    std::vector<std::thread> burners;
    for (int i = 0; i < load; ++i) burners.emplace_back([&] { volatile unsigned x = 0; while (!stop) x = x + 1; });
    double worstAhead = -1, worstCycleAhead = -1, maxStep = 0;
    int ahead = 0;
    const int runs = 40;
    for (int r = 0; r < runs; ++r) {
        double ttStart, cyStart, wallAtCross = 0, cyAtCross = 0;
        std::thread worker([&] {
            ttStart = ThreadTimesSeconds();
            cyStart = CycleSeconds();
            const auto w0 = std::chrono::steady_clock::now();
            double last = ttStart;
            volatile unsigned work = 0;
            while (true) {
                const double now = ThreadTimesSeconds();
                maxStep = std::max(maxStep, now - last);
                last = now;
                if (now - ttStart > 0.1) break;
                for (int i = 0; i < 10000; ++i) work = work + i;
            }
            wallAtCross = std::chrono::duration<double>(std::chrono::steady_clock::now() - w0).count();
            cyAtCross = CycleSeconds() - cyStart;
        });
        worker.join();
        const double over = (0.1 - wallAtCross);
        if (over > 0) ++ahead;
        worstAhead = std::max(worstAhead, over);
        worstCycleAhead = std::max(worstCycleAhead, cyAtCross - wallAtCross);
    }
    stop = true;
    for (auto& t : burners) t.join();
    std::printf("load=%d tscHz=%.0f runs=%d: GetThreadTimes passed 0.1 s before 0.1 s of wall in %d runs, by up to %.2f ms; largest GetThreadTimes step %.2f ms; QueryThreadCycleTime ahead of wall by at most %.3f ms\n",
                load, tscHz, runs, ahead, worstAhead * 1e3, maxStep * 1e3, worstCycleAhead * 1e3);
}
probe4.cpp
#include <windows.h>
#include <intrin.h>
#include <cstdio>
#include <thread>
static double Wall() { LARGE_INTEGER f, n; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&n); return double(n.QuadPart) / f.QuadPart; }
int main() {
    LARGE_INTEGER f, a, b; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&a); const auto t0 = __rdtsc(); Sleep(20); QueryPerformanceCounter(&b);
    const double hz = (__rdtsc() - t0) / (double(b.QuadPart - a.QuadPart) / f.QuadPart);
    const HANDLE event = CreateEventW(nullptr, TRUE, TRUE, nullptr);
    struct Kind { const char* name; int what; };
    for (const Kind kind : {Kind{"none", 0}, Kind{"QueryThreadCycleTime", 1}, Kind{"SwitchToThread", 2}, Kind{"WaitForSingleObject(signaled event, 0)", 3}, Kind{"GetThreadTimes", 4}}) {
        std::thread([&] {
            ULONG64 c0 = 0, c1 = 0, scratch = 0; long long calls = 0;
            FILETIME x, y, z, w;
            QueryThreadCycleTime(GetCurrentThread(), &c0);
            const double w0 = Wall();
            while (Wall() - w0 < 1.0) {
                if (kind.what == 1) QueryThreadCycleTime(GetCurrentThread(), &scratch);
                else if (kind.what == 2) SwitchToThread();
                else if (kind.what == 3) WaitForSingleObject(event, 0);
                else if (kind.what == 4) GetThreadTimes(GetCurrentThread(), &x, &y, &z, &w);
                if (kind.what != 0) ++calls;
            }
            QueryThreadCycleTime(GetCurrentThread(), &c1);
            const double wall = Wall() - w0, cpu = (c1 - c0) / hz;
            const double perCall = calls ? (wall - cpu) / calls * 1e9 : 0.0;
            std::printf("%-40s %6.2f M calls/s, cycle time %+.2f %% against wall, %.1f ns uncounted per call\n", kind.name, calls / wall / 1e6, (cpu - wall) / wall * 100, perCall);
        }).join();
    }
}

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 and the licence notice of code adapted from upstream (see AGENTS.md)
  • 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. Claude Code found the clock steps while checking a test that failed under load, wrote the change and the test, ran the probes, the tests and the mutation checks above, and drafted this description.

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5383802921 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/23238). Originally posted by [videogamer10293](https://github.com/videogamer10293) on 2026-11-18T20:45:54Z. --- ### What On Windows, the thread CPU clocks came from `GetThreadTimes`: `clock_gettime` with clock 14, and the clock `pthread_getcpuclockid` gives for a guest thread. Those times advance in 15.62 ms steps, also with the timer resolution raised to 0.5 ms, while `clock_getres` reports 1 µs for these clocks. They can also read ahead of wall time, by up to 6.45 ms in the probe below. With an invariant TSC (CPUID 0x80000007 EDX bit 8), both clocks now read [`QueryThreadCycleTime`](https://learn.microsoft.com/en-us/windows/win32/api/realtimeapiset/nf-realtimeapiset-querythreadcycletime) and divide it by the host TSC frequency that libkernel already measures for `sceKernelGetTscFrequency` (`HostTscFrequency_nid_no_patch`). Microsoft writes "Do not attempt to convert the CPU clock cycles returned by QueryThreadCycleTime to elapsed time" and documents no time unit, so the numbers below compare the result with wall time. Without an invariant TSC the clocks stay on `GetThreadTimes`. Unchanged: clocks 1 and 2 and `getrusage` report user and system time apart. A cycle count cannot split them. Clock 15 is a process-wide total, and #18471 changes it separately; its diff and this one touch different lines. The first read now measures the TSC frequency if nothing did before: that pins the calling thread to one CPU and waits 20 ms. The new debt entry records what is measured and what is not. The fragment `fix-nkwebkit-cputime.md` from merged #20139, not folded yet, said its clock comes from `GetThreadTimes` on Windows; this PR updates that text in place, since `debt_fold.py` cannot `change` an entry that is still pending. **Test.** `guest_thread_cpu_clock` gets `ThreadClocksAdvanceInSmallSteps`. A thread burns 200 ms of its own CPU time, with a short busy loop between readings of its clock, once through clock 14 and once through its `pthread_getcpuclockid` clock. Readings must not go back. The clock may not advance more than the monotonic clock plus 2% and 2 ms, nor less than the process CPU clock (clock 2) minus 10% and 31.25 ms. At least 100 readings must differ; a clock that moves in 15.62 ms steps gives about 13. A Windows host without an invariant TSC skips that last check, since the clock keeps the steps there. ### 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. --> Windows 10 Pro 10.0.19045, AMD Ryzen 5 7600X (invariant TSC bit set), NVIDIA GeForce RTX 5070 Ti for the GPU tests, WinLibs GCC 15.2.0 r7, Release. Tested on `main` `2a9d82dbf6` with the branch at `6abac1715f`. This PR's commit differs from it only in the debt entry's wording and a rebase onto newer `main`, whose new commits change none of this PR's files; the tests were not run again after that. Both trees carry the same uncommitted `_putenv_s` guard in `UploadCacheReadOnlyFlush.cpp`, without which `main` does not build on Windows (#19899, #22373 and #22634 fix it). - **Through libkernel** (`libclock.cpp` below), clock 14 on one thread for 1 s of wall time, 20 fresh processes per row. "Reads" does nothing but read the clock. "Work" spends 3.9 µs per step on a busy loop and two other system calls, and reads the clock once per millisecond. | build | loop | distinct readings per second | clock 14 against wall time | |---|---|---|---| | `main` | reads | 64 | 0.000% in all 20 | | branch | reads | 8583540 to 8656730 | -5.87% to -5.67% | | `main` | work | 64 | 0.000% in all 20 | | branch | work | 1000 to 1001 | -0.21% to -0.03% | `HostTscFrequency_nid_no_patch` ranged from 4691035024 to 4691079935 Hz over these and the loaded starts. With 12 busy threads running, the "work" thread gave most of its time away; `main`'s clock 14 did not move once in 20 runs, and the branch's gave 84 to 127 readings. - **What the "reads" loop loses.** Without any AnyPS5 library (`probe4.cpp`), a thread's cycle time divided by the TSC frequency stayed within 0.03% of wall time with no system calls (within 0.25% over the five saved runs of this probe). With about 10 million `QueryThreadCycleTime` calls a second it read 6.50% low, about 6.5 ns per call; `SwitchToThread`, `WaitForSingleObject` and `GetThreadTimes` lost 1 ns or less per call. So the clock seems to leave part of each of its own reads uncounted; the debt entry records this. - **`GetThreadTimes` without AnyPS5** (`probe.cpp`, 40 runs per row): a thread burns until `GetThreadTimes` has advanced by more than 0.1 s. Its largest step was 15.62 ms in all five rows: no load, 12 and 24 busy threads at the default timer resolution, and no load and 12 busy threads at 0.5 ms. In 5 of the 200 runs it got there before 0.1 s of wall time had passed, by up to 6.45 ms. The thread's `QueryThreadCycleTime` never read ahead. - **The new check.** `guest_thread_cpu_clock` passed on the branch 5 of 5 alone and 20 of 20 with 12 busy threads running. The branch's test executable with `main`'s libraries aborted 5 of 5; `main`'s own test executable passed 5 of 5 with the same libraries (exit code 0). - **Mutations**, each built and run 3 times: each failed the test 3 of 3: clock 14 read with `GetThreadTimes` again, a guest thread's clock read with `GetThreadTimes` again, the converted time doubled, the converted time halved, the conversion's remainder term dropped, and the invariant TSC check made to report none. The unchanged branch passed 3 of 3 before and after. - **`tools/select_tests.py`** selected the same 5400 tests on both sides, run with `-j 8`; 26 were skipped on both. Both sides failed `agc_driver_stencil_plane_memory` (#22427), `agc_driver_msaa_dcc_unwatch`, `agc_driver_bda_device` (#22773) and `nkwebkit_wtfcputime`. `main` also failed `frame_capture_minimize` and the branch `agc_driver_image_table_packed_guards`. Run again 5 times alone and 5 times with 12 busy threads on each side, those two failed once each on `main` and never on the branch. - `nkwebkit_wtfcputime` reads clock 14. It passed 20 of 20 alone on each side. With 12 busy threads it failed 8 of 20 on `main` and 13 of 20 on the branch; two earlier rounds of 20 on `main` `6286d36449` gave 7 on `main` and 9 on `f0828c0734`, then 11 on `main` and 8 on `b218c883c6`. Every failure was at line 111, which checks that the main thread's own CPU time stays under 30 ms. With the precise clock on the branch, this suggests the thread really used more than 30 ms under load; why was not examined here. Not tested: Linux and macOS, whose clock code is unchanged but where the new check also runs; Intel CPUs; a CPU without an invariant TSC; titles. `tools/pr_overlap.py` could not compare 12 open PRs that conflict with `main`; their diffs were compared by hand and none touches the changed functions. <details><summary>libclock.cpp (g++ -O2 -std=c++20 -static)</summary> ```cpp #include <windows.h> #include <cstdint> #include <cstdio> #include <string> #include <thread> struct Timespec { std::int64_t sec; std::int64_t nsec; }; using ClockGettime = int(__attribute__((sysv_abi)) *)(int, Timespec*); using TscFrequency = std::uint64_t(__attribute__((sysv_abi)) *)(); static double WallSeconds() { LARGE_INTEGER frequency, now; QueryPerformanceFrequency(&frequency); QueryPerformanceCounter(&now); return static_cast<double>(now.QuadPart) / static_cast<double>(frequency.QuadPart); } int main(int argc, char** argv) { const double burnSeconds = argc > 1 ? std::atof(argv[1]) : 1.0; const bool work = argc > 2 && std::string(argv[2]) == "work"; const HANDLE event = CreateEventW(nullptr, TRUE, TRUE, nullptr); const HMODULE kernel = LoadLibraryA("libkernel.prx"); if (kernel == nullptr) { std::printf("LoadLibrary libkernel.prx failed %lu\n", GetLastError()); return 2; } const auto clockGettime = reinterpret_cast<ClockGettime>(GetProcAddress(kernel, "clock_gettime_nid_postfix")); const auto tscFrequency = reinterpret_cast<TscFrequency>(GetProcAddress(kernel, "HostTscFrequency_nid_no_patch")); if (clockGettime == nullptr || tscFrequency == nullptr) return 3; const std::uint64_t frequency = tscFrequency(); double cpu = 0; double wall = 0; int steps = 0; long long workSteps = 0; std::thread([&] { Timespec start{}, now{}; clockGettime(14, &start); const double wallStart = WallSeconds(); std::int64_t previous = start.sec * 1000000000LL + start.nsec; double nextRead = 0; while (WallSeconds() - wallStart < burnSeconds) { if (work) { volatile unsigned x = 0; for (int i = 0; i < 20000; ++i) x = x + i; WaitForSingleObject(event, 0); SwitchToThread(); ++workSteps; if (WallSeconds() - wallStart < nextRead) continue; nextRead += 0.001; } clockGettime(14, &now); const std::int64_t value = now.sec * 1000000000LL + now.nsec; if (value != previous) ++steps; previous = value; } clockGettime(14, &now); wall = WallSeconds() - wallStart; cpu = static_cast<double>((now.sec - start.sec) * 1000000000LL + (now.nsec - start.nsec)) / 1e9; }).join(); std::printf("%s: HostTscFrequency %llu Hz; clock 14 over a %.3f s burn: %.4f s, %+.3f ms against wall (%+.3f %%), %d distinct readings, %.2f us per work step\n", work ? "work" : "reads", static_cast<unsigned long long>(frequency), wall, cpu, (cpu - wall) * 1e3, (cpu - wall) / wall * 100.0, steps, workSteps ? wall * 1e6 / static_cast<double>(workSteps) : 0.0); return 0; } ``` </details> <details><summary>probe.cpp (probe_res.cpp adds NtSetTimerResolution(5000))</summary> ```cpp #include <windows.h> #include <intrin.h> #include <atomic> #include <chrono> #include <cstdio> #include <thread> #include <vector> #include <algorithm> static double ThreadTimesSeconds() { FILETIME c, e, k, u; GetThreadTimes(GetCurrentThread(), &c, &e, &k, &u); auto t = [](FILETIME f) { return (static_cast<unsigned long long>(f.dwHighDateTime) << 32) | f.dwLowDateTime; }; return (t(k) + t(u)) * 100e-9; } static double tscHz = 0; static double CycleSeconds() { ULONG64 cycles = 0; QueryThreadCycleTime(GetCurrentThread(), &cycles); return cycles / tscHz; } int main(int argc, char** argv) { const int load = argc > 1 ? atoi(argv[1]) : 0; LARGE_INTEGER f, a, b; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&a); auto t0 = __rdtsc(); Sleep(200); QueryPerformanceCounter(&b); auto t1 = __rdtsc(); tscHz = (t1 - t0) / (double(b.QuadPart - a.QuadPart) / f.QuadPart); std::atomic<bool> stop{false}; std::vector<std::thread> burners; for (int i = 0; i < load; ++i) burners.emplace_back([&] { volatile unsigned x = 0; while (!stop) x = x + 1; }); double worstAhead = -1, worstCycleAhead = -1, maxStep = 0; int ahead = 0; const int runs = 40; for (int r = 0; r < runs; ++r) { double ttStart, cyStart, wallAtCross = 0, cyAtCross = 0; std::thread worker([&] { ttStart = ThreadTimesSeconds(); cyStart = CycleSeconds(); const auto w0 = std::chrono::steady_clock::now(); double last = ttStart; volatile unsigned work = 0; while (true) { const double now = ThreadTimesSeconds(); maxStep = std::max(maxStep, now - last); last = now; if (now - ttStart > 0.1) break; for (int i = 0; i < 10000; ++i) work = work + i; } wallAtCross = std::chrono::duration<double>(std::chrono::steady_clock::now() - w0).count(); cyAtCross = CycleSeconds() - cyStart; }); worker.join(); const double over = (0.1 - wallAtCross); if (over > 0) ++ahead; worstAhead = std::max(worstAhead, over); worstCycleAhead = std::max(worstCycleAhead, cyAtCross - wallAtCross); } stop = true; for (auto& t : burners) t.join(); std::printf("load=%d tscHz=%.0f runs=%d: GetThreadTimes passed 0.1 s before 0.1 s of wall in %d runs, by up to %.2f ms; largest GetThreadTimes step %.2f ms; QueryThreadCycleTime ahead of wall by at most %.3f ms\n", load, tscHz, runs, ahead, worstAhead * 1e3, maxStep * 1e3, worstCycleAhead * 1e3); } ``` </details> <details><summary>probe4.cpp</summary> ```cpp #include <windows.h> #include <intrin.h> #include <cstdio> #include <thread> static double Wall() { LARGE_INTEGER f, n; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&n); return double(n.QuadPart) / f.QuadPart; } int main() { LARGE_INTEGER f, a, b; QueryPerformanceFrequency(&f); QueryPerformanceCounter(&a); const auto t0 = __rdtsc(); Sleep(20); QueryPerformanceCounter(&b); const double hz = (__rdtsc() - t0) / (double(b.QuadPart - a.QuadPart) / f.QuadPart); const HANDLE event = CreateEventW(nullptr, TRUE, TRUE, nullptr); struct Kind { const char* name; int what; }; for (const Kind kind : {Kind{"none", 0}, Kind{"QueryThreadCycleTime", 1}, Kind{"SwitchToThread", 2}, Kind{"WaitForSingleObject(signaled event, 0)", 3}, Kind{"GetThreadTimes", 4}}) { std::thread([&] { ULONG64 c0 = 0, c1 = 0, scratch = 0; long long calls = 0; FILETIME x, y, z, w; QueryThreadCycleTime(GetCurrentThread(), &c0); const double w0 = Wall(); while (Wall() - w0 < 1.0) { if (kind.what == 1) QueryThreadCycleTime(GetCurrentThread(), &scratch); else if (kind.what == 2) SwitchToThread(); else if (kind.what == 3) WaitForSingleObject(event, 0); else if (kind.what == 4) GetThreadTimes(GetCurrentThread(), &x, &y, &z, &w); if (kind.what != 0) ++calls; } QueryThreadCycleTime(GetCurrentThread(), &c1); const double wall = Wall() - w0, cpu = (c1 - c0) / hz; const double perCall = calls ? (wall - cpu) / calls * 1e9 : 0.0; std::printf("%-40s %6.2f M calls/s, cycle time %+.2f %% against wall, %.1f ns uncounted per call\n", kind.name, calls / wall / 1e6, (cpu - wall) / wall * 100, perCall); }).join(); } } ``` </details> ### 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) and the licence notice of code adapted from upstream (see AGENTS.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. Claude Code found the clock steps while checking a test that failed under load, wrote the change and the test, ran the probes, the tests and the mutation checks above, and drafted this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
PrivacyOnion commented 2026-11-18 21:00:40 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by PrivacyOnion on 2026-11-18T21:00:40Z.

Review: APPROVED


Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against beb0afc706:

  • Conventions: tools/check_conventions.py passed.
  • Build: guest_thread_cpu_clock_tests built cleanly.
  • CTest (guest_thread_cpu_clock):
    1/1 Test #5493: guest_thread_cpu_clock ...........   Passed    2.22 sec
    100% tests passed, 0 tests failed out of 1
    
  • Negative control: with core/libs/prx/libkernel/Pthread/src/Thread.cpp, core/libs/prx/libkernel/Time/Time.cpp, core/libs/prx/libkernel/Time/include/Time.hpp reverted to main and the new tests kept, the suite fails:
    1/1 Test #5493: guest_thread_cpu_clock ...........   Passed    1.60 sec
    100% tests passed, 0 tests failed out of 1
    
    Restoring the change makes it pass again.
  • Code reading:
    • Verified HostThreadCpuNanos_nid_no_patch handles QueryThreadCycleTime failure and GetThreadTimes failure, correctly returning false and propagating errors to ThreadCpuTimeNanos.
    • Verified integer arithmetic in cycle-to-nanoseconds conversion (cycles / frequency * 1000000000ULL + cycles % frequency * 1000000000ULL / frequency) correctly avoids 64-bit integer overflow.
    • Verified InvariantTsc CPUID check against bit 8 of EDX on leaf 0x80000007 after checking maximum leaf >= 0x80000007.
    • Verified ClockTimeWin32ErrorToGuestErrno_nid_no_patch is correctly called when HostThreadCpuNanos_nid_no_patch returns false in ThreadCpuTimeNanos.
    • Verified ReadClock correctly branches clock 14 to ThreadCpuTimeNanos and clock 15 to ProcessCpuTimeNanos.
    • Verified technical debt entries in docs/dev/debt/changes/ follow repository fragment format and AGENTS.md requirements.

Looks Good To Me

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5965069875 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/23238#pullrequestreview-5965069875). Originally posted by [PrivacyOnion](https://github.com/PrivacyOnion) on 2026-11-18T21:00:40Z. **Review:** APPROVED --- Verified on Linux (Ubuntu 24.04, GCC 13.3, Ninja, Release) against `beb0afc706`: - **Conventions**: `tools/check_conventions.py` passed. - **Build**: `guest_thread_cpu_clock_tests` built cleanly. - **CTest** (`guest_thread_cpu_clock`): ``` 1/1 Test #5493: guest_thread_cpu_clock ........... Passed 2.22 sec 100% tests passed, 0 tests failed out of 1 ``` - **Negative control**: with `core/libs/prx/libkernel/Pthread/src/Thread.cpp`, `core/libs/prx/libkernel/Time/Time.cpp`, `core/libs/prx/libkernel/Time/include/Time.hpp` reverted to `main` and the new tests kept, the suite fails: ``` 1/1 Test #5493: guest_thread_cpu_clock ........... Passed 1.60 sec 100% tests passed, 0 tests failed out of 1 ``` Restoring the change makes it pass again. - **Code reading**: - Verified HostThreadCpuNanos_nid_no_patch handles QueryThreadCycleTime failure and GetThreadTimes failure, correctly returning false and propagating errors to ThreadCpuTimeNanos. - Verified integer arithmetic in cycle-to-nanoseconds conversion (cycles / frequency * 1000000000ULL + cycles % frequency * 1000000000ULL / frequency) correctly avoids 64-bit integer overflow. - Verified InvariantTsc CPUID check against bit 8 of EDX on leaf 0x80000007 after checking maximum leaf >= 0x80000007. - Verified ClockTimeWin32ErrorToGuestErrno_nid_no_patch is correctly called when HostThreadCpuNanos_nid_no_patch returns false in ThreadCpuTimeNanos. - Verified ReadClock correctly branches clock 14 to ThreadCpuTimeNanos and clock 15 to ProcessCpuTimeNanos. - Verified technical debt entries in docs/dev/debt/changes/ follow repository fragment format and AGENTS.md requirements. Looks Good To Me
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!23238
No description provided.