GeezerVison is showing w3c.github.io — High Resolution Time
1.
Introduction
This section is non-normative.
The ECMAScript Language specification [ECMA-262] defines the
Date object as a time value
representing time in milliseconds since 01 January, 1970 UTC. For most
purposes, this definition of time is sufficient as these values
represent time to millisecond precision for any moment that is within
approximately 285,616 years from 01 January, 1970 UTC.
In practice, these definitions of time are subject to both clock skew
and adjustment of the system clock. The value of time may not always be
monotonically increasing and subsequent values may either decrease or
remain the same.
For example, the following script may record a positive number,
negative number, or zero for computed duration:
var mark_start = Date.now();
doTask();// Some taskvar duration = Date.now()- mark_start;
For certain tasks this definition of time may not be sufficient as it:
Does not have a stable monotonic clock, and as a result, it is
subject to system clock skew.
Does not provide sub-millisecond time resolution.
This specification does not propose changing the behavior of
Date.now()[ECMA-262] as it is
genuinely useful in determining the current value of the calendar time
and has a long history of usage. The DOMHighResTimeStamp type,
Performance.now() method, and
Performance.timeOrigin attributes of the
Performance interface resolve the above issues by providing
monotonically increasing time values with sub-millisecond resolution.
Providing sub-millisecond resolution is not a mandatory part of this
specification. Implementations may choose to limit the timer resolution
they expose for privacy and security reasons, and not expose
sub-millisecond timers. Use-cases that rely on sub-millisecond
resolution may not be satisfied when that happens.
1.1.
Use-cases
This section is non-normative.
This specification defines a few different capabilities: it provides
timestamps based on a stable, monotonic clock, comparable across
contexts, with potential sub-millisecond resolution.
The need for a stable monotonic clock when talking about performance
measurements stems from the fact that unrelated clock skew can
distort measurements and render them useless. For example, when
attempting to accurately measure the elapsed time of navigating to a
Document, fetching of resources or execution of script, a
monotonically increasing clock with sub-millisecond resolution is
desired.
Comparing timestamps between contexts is essential e.g. when
synchronizing work between a Worker and the main thread or when
instrumenting such work in order to create a unified view of the
event timeline.
Finally, the need for sub-millisecond timers revolves around the
following use-cases:
Ability to schedule work in sub-millisecond intervals. That is
particularly important on the main thread, where work can interfere
with frame rendering which needs to happen in short and regular
intervals, to avoid user-visible jank.
When calculating the frame rate of a script-based animation,
developers will need sub-millisecond resolution in order to determine
if an animation is drawing at 60 FPS. Without sub-millisecond
resolution, a developer can only determine if an animation is drawing
at 58.8 FPS (1000ms / 16) or 62.5 FPS (1000ms / 17).
When collecting in-the-wild measurements of JS code (e.g. using
User-Timing), developers may be interested in gathering
sub-milliseconds timing of their functions, to catch regressions
early.
When attempting to cue audio to a specific point in an animation
or ensure that the audio and animation are perfectly synchronized,
developers will need to accurately measure the amount of time
elapsed.
1.2.
Examples
This section is non-normative.
A developer may wish to construct a timeline of their entire
application, including events from Worker or SharedWorker,
which have different time origins. To
display such events on the same timeline, the application can
translate the DOMHighResTimeStamps with the help of the
Performance.timeOrigin attribute.
// ---- worker.js -----------------------------// Shared worker script
onconnect =function(e){var port = e.ports[0];
port.onmessage =function(e){// Time execution in workervar task_start = performance.now();
result = runSomeWorkerTask();var task_end = performance.now();}// Send results and epoch-relative timestamps to another context
port.postMessage({'task':'Some worker task','start_time': task_start + performance.timeOrigin,'end_time': task_end + performance.timeOrigin,'result': result
});}// ---- application.js ------------------------// Timing tasks in the documentvar task_start = performance.now();
runSomeApplicationTask();var task_end = performance.now();// developer provided method to upload runtime performance data
reportEventToAnalytics({'task':'Some document task','start_time': task_start,'duration': task_end - task_start
});// Translating worker timestamps into document's time originvar worker =new SharedWorker('worker.js');
worker.port.onmessage =function(event){var msg = event.data;// translate epoch-relative timestamps into document's time origin
msg.start_time = msg.start_time - performance.timeOrigin;
msg.end_time = msg.end_time - performance.timeOrigin;
reportEventToAnalytics(msg);}
2.
Time Concepts
2.1.
Clocks
A clock tracks the passage of time and can report the
unsafe current time that an algorithm step is executing.
There are many kinds of clocks. All clocks on the web platform
attempt to count 1 millisecond of clock time per 1 millisecond of
real-world time, but they differ in how they handle cases where they
can’t be exactly correct.
The wall clock’s unsafe current time
is always as close as possible to a user’s notion of time. Since a computer sometimes runs slow or fast or loses track of time, its wall clock sometimes needs to be adjusted, which means the unsafe current time can decrease, making it unreliable for performance measurement or recording the orders of events. The web platform shares a wall clock with [ECMA-262]time.
The monotonic clock’s unsafe current time
never decreases, so it can’t be changed by system clock adjustments. The monotonic clock only exists within a single execution of the user agent, so it can’t be used to compare events that might happen in different executions.
Since the monotonic clock can’t be adjusted to match the user’s notion of time, it should be used for measurement, rather than user-visible times. For any time communication with the user, use the wall clock.
The user agent can pick a new estimated monotonic time of the Unix epoch when the browser restarts, when it starts an isolated browsing session—e.g. incognito or a similar browsing mode—or when it creates an environment settings object that can’t communicate with any existing settings objects. As a result, developers should not use shared timestamps as absolute time that holds its monotonic properties across all past, present, and future contexts; in practice, the monotonic properties only apply for contexts that can reach each other by exchanging messages via one of the provided messaging mechanisms - e.g. postMessage(message, options), BroadcastChannel, etc.
In certain scenarios (e.g. when a tab is backgrounded), the user agent may choose to throttle timers and periodic callbacks run in that context or even freeze them entirely. Any such throttling should not affect the resolution or accuracy of the time returned by the monotonic clock.
Moments and unsafe moments represent points in time, which
means they can’t be directly stored as numbers. Implementations will
usually represent a moment as a duration from some other
fixed point in time, but specifications ought to deal in the
moments themselves.
Return the amount of time from a to b as a duration. If
b came before a, this will be a negative duration.
Durations can be used implicitly as DOMHighResTimeStamps. To
implicitly convert a duration to a timestamp, given a
durationd, return the number of milliseconds in d.
Avoid sending similar representations between computers, as doing so
will expose the user’s clock skew, which is a tracking vector.
Instead, use an approach similar to monotonic clockmoments of
sending a duration between two moments.
3.1.
Examples
The time a DOM event happens can be reported using:
If context’s current wall time is less than source’s source time + source’s expiry,
send a report.
4.
Time Origin
The Unix epoch is the moment on the
wall clock corresponding to 1 January 1970 00:00:00 UTC.
Each group of environment settings objects that could possibly
communicate in any way has an estimated monotonic time of the Unix
epoch, a moment on the monotonic clock, whose value is
initialized by the following steps:
The value returned by get time origin timestamp is approximately
the time after the Unix epoch that global’s time origin happened. It may differ from the value
returned by Date.now() executed at the time origin, because the
former is recorded with respect to a monotonic clock that is not
subject to system and user clock adjustments, clock skew, and so on.
The coarsen time algorithm, given an unsafe momenttimestamp on some clock and an optional
boolean crossOriginIsolatedCapability (default false), runs
the following steps:
The coarsened shared current time given an
optional boolean crossOriginIsolatedCapability (default
false), must return the result of calling coarsen time with the
unsafe shared current time and crossOriginIsolatedCapability.
A DOMHighResTimeStamp SHOULD represent a time in milliseconds
accurate enough to allow measurement while preventing timing attacks -
see § 11.1 Clock resolution for additional considerations.
A DOMHighResTimeStamp is a double, so it can only represent an
epoch-relative time—the number of milliseconds from the Unix epoch
to a moment—to a finite resolution. For moments in 2023, that
resolution is approximately 0.2 microseconds.
A EpochTimeStamp represents an integral number of milliseconds from
the Unix epoch to a given moment on the wall clock,
excluding leap seconds. Specifications that use this type define how
the number of milliseconds are interpreted.
The time values returned when calling the now()
method on Performance or WorkletPerformance objects with the
same time origin MUST use the same
monotonic clock. The difference between any two chronologically
recorded time values returned from the now() method
MUST never be negative if the two time values have the same
time origin.
Access to accurate timing information, both for measurement and
scheduling purposes, is a common requirement for many applications.
For example, coordinating animations, sound, and other activity on
the page requires access to high-resolution time to provide a good
user experience. Similarly, measurement enables developers to track
the performance of critical code components, detect regressions, and
so on.
However, access to the same accurate timing information can sometimes
be also used for malicious purposes by an attacker to guess and infer
data that they can’t see or access otherwise. For example, cache
attacks, statistical fingerprinting and micro-architectural attacks
are a privacy and security concern where a malicious web site may use
high resolution timing data of various browser or
application-initiated operations to differentiate between subset of
users, identify a particular user or reveal unrelated but
same-process user data - see [CACHE-ATTACKS] and [SPECTRE] for
more background.
This specification defines an API that provides sub-millisecond time
resolution, which is more accurate than the previously available
millisecond resolution exposed by EpochTimeStamp. However, even
without this new API an attacker may be able to obtain
high-resolution estimates through repeat execution and statistical
analysis.
To ensure that the new API does not significantly improve the
accuracy or speed of such attacks, the minimum resolution of the
DOMHighResTimeStamp type should be inaccurate enough to prevent
attacks.
Where necessary, the user agent should set higher resolution values
to time resolution in coarsen time’s processing model, to
address privacy and security concerns due to architecture or software
constraints, or other considerations.
In order to mitigate such attacks user agents may deploy any
technique they deem necessary. Deployment of those techniques may
vary based on the browser’s architecture, the user’s device, the
content and its ability to maliciously read cross-origin data, or
other practical considerations.
These techniques may include:
Resolution reduction.
Added jitter.
Abuse detection and/or API call throttling.
Mitigating such timing side-channel attacks entirely is practically
impossible: either all operations would have to execute in a time
that does not vary based on the value of any confidential
information, or the application would need to be isolated from any
time-related primitives (clock, timers, counters, etc). Neither is
practical due to the associated complexity for the browser and
application developers and the associated negative effects on
performance and responsiveness of applications.
Clock resolution is an unsolved and evolving area of research, with
no existing industry consensus or definitive set of recommendations
that applies to all browsers. To track the discussion, refer to
Issue 79.
11.2.
Clock drift
This specification also defines an API that provides sub-millisecond
time resolution of the zero time of the time origin, which requires
and exposes a monotonic clock to the application, and that
must be shared across all the browser contexts. The monotonic clock does not need to be tied to physical time, but is
recommended to be set with respect to the [ECMA-262] definition of
time to avoid exposing new fingerprint entropy about the user
— e.g. this time can already be easily obtained by the application,
whereas exposing a new logical clock provides new information.
However, even with the above mechanism in place, the monotonic clock may provide additional clock drift
resolution. Today, the application can timestamp the time-of-day and
monotonic time values (via Date.now() and
now()) at multiple points within the same context and
observe drift between them—e.g. due to automatic or user clock
adjustments. With the timeOrigin attribute, the
attacker can also compare the time origin, as reported by the monotonic clock, against the
current time-of-day estimate of the time origin (i.e. the difference between
`performance.timeOrigin` and `Date.now() - performance.now()`) and
potentially observe clock drift between these clocks over a longer
time period.
In practice, the same time drift can be observed by an application
across multiple navigations: the application can record the logical
time in each context and use a client or server time synchronization
mechanism to infer changes in the user’s clock. Similarly,
lower-layer mechanisms such as TCP timestamps may reveal the same
high-resolution information to the server without the need for
multiple visits. As such, the information provided by this API should
not expose any significant or previously unavailable entropy about
the user.
12.
Privacy Considerations
This section is non-normative.
The current definition of time origin
for a Document exposes the total time of cross-origin redirects
prior to the request arriving at the document’s origin. This exposes
cross-origin information, however it’s not yet decided how to mitigate
this without causing major breakages to performance metrics.
Thanks to Arvind Jain, Angelos D. Keromytis, Boris Zbarsky, Jason
Weber, Karen Anderson, Nat Duca, Philippe Le Hegaret, Ryosuke Niwa,
Simha Sethumadhavan, Todd Reifsteck, Tony Gentilcore, Vasileios P.
Kemerlis, Yoav Weiss, and Yossef Oren for their contributions to this
work.
You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.