From 1cd3af43fd74a8481b35d58c351ae056c1cba362 Mon Sep 17 00:00:00 2001 From: Krzysztof Antonowski Date: Mon, 2 Feb 2026 22:19:19 +0100 Subject: [PATCH] std.Io.Threaded: implement CPU-based clocks on Windows (#31093) Reviewed-on: https://codeberg.org/ziglang/zig/pulls/31093 Co-authored-by: Krzysztof Antonowski Co-committed-by: Krzysztof Antonowski --- lib/std/Io/Threaded.zig | 37 ++++++++++++++++++++++++++++++++++--- lib/std/os/windows.zig | 8 ++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/lib/std/Io/Threaded.zig b/lib/std/Io/Threaded.zig index 298c3c167f6e6c044d41cf1e83e03f3664e54df6..3f4affcc5ca17b83d5cb99b398b735c363cd4919 100644 --- a/lib/std/Io/Threaded.zig +++ b/lib/std/Io/Threaded.zig @@ -10849,9 +10849,40 @@ fn nowWindows(clock: Io.Clock) Io.Clock.Error!Io.Timestamp { const result = (@as(u96, qpc) * scale) >> 32; return .{ .nanoseconds = @intCast(result) }; }, - .cpu_process, - .cpu_thread, - => return error.UnsupportedClock, + .cpu_process => { + const handle = windows.GetCurrentProcess(); + var times: windows.KERNEL_USER_TIMES = undefined; + + // https://github.com/reactos/reactos/blob/master/ntoskrnl/ps/query.c#L442-L485 + if (windows.ntdll.NtQueryInformationProcess( + handle, + windows.PROCESSINFOCLASS.Times, + ×, + @sizeOf(windows.KERNEL_USER_TIMES), + null, + ) != .SUCCESS) + return error.Unexpected; + + const sum = @as(i96, times.UserTime) + @as(i96, times.KernelTime); + return .{ .nanoseconds = sum * 100 }; + }, + .cpu_thread => { + const handle = windows.GetCurrentThread(); + var times: windows.KERNEL_USER_TIMES = undefined; + + // https://github.com/reactos/reactos/blob/master/ntoskrnl/ps/query.c#L2971-L3019 + if (windows.ntdll.NtQueryInformationThread( + handle, + windows.THREADINFOCLASS.Times, + ×, + @sizeOf(windows.KERNEL_USER_TIMES), + null, + ) != .SUCCESS) + return error.Unexpected; + + const sum = @as(i96, times.UserTime) + @as(i96, times.KernelTime); + return .{ .nanoseconds = sum * 100 }; + }, } } diff --git a/lib/std/os/windows.zig b/lib/std/os/windows.zig index b9653b3ac9979d9eb5144822fb7ed27f802a55a7..0f57eed766eba130ece4bafc3b76e5684de2239b 100644 --- a/lib/std/os/windows.zig +++ b/lib/std/os/windows.zig @@ -6191,6 +6191,14 @@ pub const PROCESS_BASIC_INFORMATION = extern struct { InheritedFromUniqueProcessId: ULONG_PTR, }; +// https://github.com/reactos/reactos/blob/master/sdk/include/ndk/pstypes.h#L977-L983 +pub const KERNEL_USER_TIMES = extern struct { + CreationTime: LARGE_INTEGER, + ExitTime: LARGE_INTEGER, + KernelTime: LARGE_INTEGER, + UserTime: LARGE_INTEGER, +}; + pub const ReadMemoryError = error{ Unexpected, }; -- 2.54.0