今日已更新 240 条资讯 | 累计 23823 条内容
关于我们

Your Clock Can Go Backward—Use the Right One for Durations

Luciano Menezes 2026年07月21日 20:39 4 次阅读 来源:Dev.to

A request starts at 10:00:00.900 and finishes 200 ms later. Your latency log says -800 ms . That sounds impossible until the machine corrects its clock between the two reads. Then ordinary code turns an adjustable wall clock into a broken stopwatch. The subtraction that works—until it does not This is probably hiding in one of your metrics helpers: async function timed ( operation ) { const startedAt = Date . now (); const result = await operation (); return { result , durationMs : Date . now () - startedAt , }; } Most of the time, this reports a sensible number. That is what makes it dangerous. Date.now() answers a calendar question: how many milliseconds have passed since the Unix epoch according to this machine? The answer must remain comparable with logs, users, and other computers, so synchronization software is allowed to correct it. A correction can change its rate, jump it forward, or move it backward. If either correction lands between the two calls, the subtraction measures the clock adjustment as if it were work. A timestamp is a coordinate. A duration is a distance. They need different instruments. Your computer already has two kinds of clock Operating systems expose several clocks, but two mental buckets cover most application code: Question Clock JavaScript example “When did this happen?” Wall clock Date.now() , new Date() “How long did this take?” Monotonic clock performance.now() A wall clock follows civil time. It has an epoch and can be serialized as an ISO timestamp. A monotonic clock starts at an arbitrary origin and promises that later readings will not be lower than earlier readings. wall: 1000 ── 1001 ── 0998 ── 0999 clock correction monotonic: 40 ───── 41 ───── 42 ───── 43 On Linux, CLOCK_REALTIME is settable wall time . CLOCK_MONOTONIC cannot be set and does not make discontinuous jumps backward, although gradual frequency adjustment can affect its rate. Linux even has CLOCK_BOOTTIME for a monotonic counter that includes suspended time. Thre

本文内容来源于互联网,版权归原作者所有
查看原文