Files

1.9 KiB

Back to Twitter thread index


title: "Renovating CPU clock code. I'm assuming x86-64 TSC is always >= 1 GHz so that co" author: "NOTimothyLottes" handle: "@NOTimothyLottes" post_url: "https://x.com/NOTimothyLottes/status/2060730425929080874" post_id: "2060730425929080874" timestamp: "2026-05-30 14:29:54" post_count: 6 reply_count: 3 repost_count: 0 like_count: 40 view_count: 4744

@NOTimothyLottes — Renovating CPU clock code. I'm assuming x86-64 TSC is always >= 1 GHz so that co

Post 1 (2026-05-30 14:29:54)

Renovating CPU clock code. I'm assuming x86-64 TSC is always >= 1 GHz so that conversion of clock counter diff to nanoseconds is simply a MUL instruction fetching the RDX high 64-bit result (of the 128-bit computed). But figuring out how to do the inline asm was a pain.

Media 1

Post 2 (2026-05-30 15:16:24) — reply to Post 1

Looks like NtQuerySystemInformation() with SystemHypervisorSharedPageInformation (aka 0xc5) gives 64-bit scalar for TSC that converts time to units of 10 MHz. So the smart way is to work in units of TSC, then do a subtraction of TSC terms, then MULHI to get {ms, us, or ns} time

Post 3 (2026-05-30 15:59:17) — reply to Post 2

https://gist.github.com/pmttavara/6f06fc5c7679c07375483b06bb77430c - A great reference for getting TSC scaling multipliers on Linux and Windows

Post 4 (2026-05-31 00:46:04) — reply to Post 1

@NOTimothyLottes If you do the multiply in uint128_t and then right-shift by 64 places, the compiler should do the right thing.

Post 5 (2026-05-31 01:37:00) — reply to Post 4

@FUZxxl “Should” is exactly why I prefer the actual instruction instrinsics or just inline asm (which is what I use on C CPU land)

Post 6 (2026-05-31 08:23:19) — reply to Post 5

@NOTimothyLottes Have fun with a solution that the compiler optimises worse and that is not portable.