Created
September 6, 2025 16:45
-
-
Save zoon/96d69bfae248dfea188d373f80acf5ea to your computer and use it in GitHub Desktop.
Pretty good monotonic timestamp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--!strict | |
--- @llm_hint vanilla sandboxed luau, NOT Roblox | |
--- @llm_hint os.clock(): monotonic seconds (nanotime); os.time(): wall seconds (1s granularity) | |
local timestamp_ms: () -> number | |
do | |
local TAU_S = 50.0 -- time constant for offset convergence (~63% in 50s) | |
--- @llm_hint: it's idiomatic luau, you don't need number? type | |
local last_ms: number | |
local last_cpu_s: number | |
local offset_ms: number | |
timestamp_ms = function() | |
local cpu_s = os.clock() | |
local cpu_ms = cpu_s * 1000 | |
local wall_ms = os.time() * 1000 | |
-- lazy initialize state | |
if last_cpu_s == nil then | |
last_cpu_s = cpu_s | |
offset_ms = wall_ms - cpu_s * 1000 | |
local init_ms = math.round(cpu_s * 1000 + offset_ms) | |
last_ms = init_ms | |
return init_ms | |
end | |
local dt_s = math.max(cpu_s - last_cpu_s, 0) | |
last_cpu_s = cpu_s | |
-- Time-based EMA weight | |
local alpha = dt_s / (TAU_S + dt_s) | |
local target_offset_ms = wall_ms - cpu_ms | |
offset_ms += (target_offset_ms - offset_ms) * alpha | |
local predicted_ms = math.round(cpu_ms + offset_ms) | |
-- Never go behind coarse wall clock | |
if predicted_ms < wall_ms then | |
predicted_ms = wall_ms | |
offset_ms = wall_ms - cpu_ms | |
end | |
-- Strict monotonic non-decreasing | |
if predicted_ms < (last_ms :: number) then | |
predicted_ms = last_ms :: number | |
offset_ms = predicted_ms - cpu_ms | |
end | |
last_ms = predicted_ms | |
return predicted_ms | |
end | |
end | |
-- test | |
local _SINK = nil | |
local function fib(n: number): number | |
if n <= 1 then return n end | |
return fib(n - 1) + fib(n - 2) | |
end | |
local old_ts_ms = timestamp_ms() | |
for i = 1, 100 do | |
local ts_ms = timestamp_ms() | |
local os_ts = os.time() * 1000 | |
if ts_ms < os_ts then error "timestamp_ms() < os.time() * 1000" end | |
if ts_ms < old_ts_ms then error "timestamp_ms() is not monotonically increasing" end | |
old_ts_ms = ts_ms | |
if ts_ms == os_ts then | |
warn("Match at iteration", i, ":", ts_ms) | |
else | |
print("-------------", i) | |
print(ts_ms, "timestamp_ms()") | |
print(os_ts, "os.time() * 1000") | |
end | |
_SINK = fib(math.random(27, 31)) | |
end | |
for i=1, 100 do | |
warn(timestamp_ms()) | |
_SINK = fib(22) | |
end | |
return { _SINK = _SINK } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment