CARVIEW |
High Resolution Time Level 2
W3C Recommendation
- This version:
- https://www.w3.org/TR/2019/REC-hr-time-2-20191121/
- Latest published version:
- https://www.w3.org/TR/hr-time-2/
- Latest editor's draft:
- https://w3c.github.io/hr-time/
- Test suite:
- https://wpt.fyi/hr-time/
- Implementation report:
- https://wpt.fyi/hr-time/
- Previous version:
- https://www.w3.org/TR/2019/PR-hr-time-2-20191015/
- Editor:
- Ilya Grigorik (Google Inc.)
- Former editors:
- James Simonsen (Google Inc.) (Until January 2015)
- Jatinder Mann (Microsoft Corp.) (Until February 2014)
- Participate:
- GitHub w3c/hr-time
- File a bug
- Commit history
- Pull requests
- Browser support:
- caniuse.com
Please check the errata for any errors or issues reported since publication.
See also translations.
Copyright © 2019 W3C® (MIT, ERCIM, Keio, Beihang). W3C liability, trademark and permissive document license rules apply.
Abstract
This specification defines an API that provides the time origin, and current time in sub-millisecond resolution, such that it is not subject to system clock skew or adjustments.
Status of This Document
This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.
High Resolution Time Level 2 replaces the first version of High Resolution Time and includes:
- A precise definition of time origin for the purpose of all performance timeline related specifications;
, an attribute providing the global time of the zero time of time origin;Performance
.timeOrigin
- The base definition for the
interface, previously specified in [PERFORMANCE-TIMELINE-20131212], is now moved to this specification and now includes support for thePerformance
method inPerformance
.now
Worker
.
This document was published by the Web Performance Working Group as a Recommendation.
GitHub Issues are preferred for discussion of this specification.
Please see the Working Group's implementation report.
This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.
This document was produced by a group operating under the W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.
This document is governed by the 1 March 2019 W3C Process Document.
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 instant that is within approximately
285,616 years from 01 January, 1970 UTC. The DOMTimeStamp
is defined
similarly [WEBIDL].
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 task
var duration = Date.now() - mark_start;
For certain tasks this definition of time may not be sufficient as it does not allow for sub-millisecond resolution and is subject to system clock skew. 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.
- When calculating the animation state from script, developers will need to accurately know the amount of time that has elapsed in the animation in order to properly update the next scene of the animation.
- 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 or 62.5 FPS.
- When attempting to cue audio to a specific point in an animation or ensure that the audio is synchronized with the animation, developers will need to accurately know the amount of time elapsed in the animation and audio.
- When multiple contexts need to synchronize work with sub-millisecond
resolution (e.g. when using
Worker
orSharedWorker
workers to drive animation, audio, etc., in a renderer context), or to create a unified view of the event timeline.
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
type,
DOMHighResTimeStamp
performance.
method, and now
performance.
attributes of
the timeOrigin
interface resolve the above issues by providing
monotonically increasing time values with sub-millisecond resolution.Performance
1.1 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
s
with the help of the DOMHighResTimeStamp
performance.
attribute.timeOrigin
// ---- worker.js -----------------------------
// Shared worker script
onconnect = function(e) {
var port = e.ports[0];
port.onmessage = function(e) {
// Time execution in worker
var 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 document
var 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 origin
var 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 Origin
The time origin is the time value from which time is measured:
- If the global object is a
Window
object, the time origin MUST be equal to:- the time when the browsing context is first created if there is no previous document;
- otherwise, the time of the user confirming the navigation during the previous document's prompt to unload algorithm, if a previous document exists and if the confirmation dialog was displayed;
- otherwise, the time of starting the navigation responsible for loading the Window object's newest Document object.
- If the global object is a
WorkerGlobalScope
object, the time origin MUST be equal to the official moment of creation of the worker. - Otherwise, the time origin is undefined.
The time origin timestamp is the high resolution time value at which time origin is zero. To obtain the time origin timestamp given a global object (global):
- Assert that global's time origin is not undefined.
- Let t1 be the
representing the high resolution time at which the global monotonic clock is zero.DOMHighResTimeStamp
- Let t2 be the
representing the high resolution time value of the global monotonic clock at global's time origin.DOMHighResTimeStamp
- Return the sum of t1 and t2.
The time origin timestamp and the value returned by
Date.now()
executed at "zero time" can differ because the former is
recorded with respect to a global monotonic clock that is not subject to
system and user clock adjustments, clock skew, and so on—see § 6. Monotonic Clock.
The current high resolution time is the high resolution time from the time origin to the present time (typically called "now").
3. The DOMHighResTimeStamp
typedef
The
type is used to store a time value in
milliseconds, measured relative from the time origin, global
monotonic clock, or a time value that represents a duration between two
DOMHighResTimeStamp
s.DOMHighResTimeStamp
typedef double DOMHighResTimeStamp
;
A
SHOULD represent a time in milliseconds
accurate enough to allow measurement while preventing timing attacks - see
§ 7.1 Clock resolution for additional considerations.DOMHighResTimeStamp
4. The Performance
interface
[Exposed=(Window,Worker)]
interface Performance
: EventTarget {
DOMHighResTimeStamp
now
();
readonly attribute DOMHighResTimeStamp
timeOrigin
;
[Default] object toJSON
();
};
4.1 now()
method
The
now()
method MUST return the current high resolution
time.
4.2 timeOrigin
attribute
The
timeOrigin
attribute MUST return a
representing the high resolution time of the time origin timestamp
for the relevant global object of the DOMHighResTimeStamp
object.Performance
4.3 toJSON()
method
When toJSON()
is
called, run [WEBIDL]'s default toJSON operation.
5. Extensions to WindowOrWorkerGlobalScope
mixin
5.1 The performance
attribute
The performance
attribute on the interface mixin
allows access to performance related
attributes and methods from the global object.WindowOrWorkerGlobalScope
partial interface mixin WindowOrWorkerGlobalScope {
[Replaceable] readonly attribute Performance performance
;
};
6. Monotonic Clock
The time values returned when calling the now
()
method on
objects with the same time origin MUST use the same
monotonic clock that is monotonically increasing
and not subject to system clock adjustments or system clock skew. The
difference between any two chronologically recorded time values returned
from the Performance
.Performance
now
()
method MUST never be negative if the two
time values have the same time origin.
The time values returned when
getting performance.
MUST use the same global monotonic clock that is shared by time origins, is
monotonically increasing and not subject to system clock adjustments or
system clock skew, and whose reference point is the [ECMA-262]
time definition - see
§ 7. Privacy and Security.timeOrigin
The user agent can reset its global monotonic clock across
browser restarts, or whenever starting an isolated browsing session—e.g.
incognito or similar browsing mode. As a result, developers should not use
global 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
,
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.
7. Privacy and Security
7.1 Clock resolution
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 microarchitectural 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 DOMTimeStamp
.
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
type should be inaccurate enough to prevent
attacks: the current minimum recommended resolution is no less than 5
microseconds and, where necessary, should be set higher by the User
Agent to address privacy and security concerns due to architecture or
software constraints, or other considerations.DOMHighResTimeStamp
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.
7.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 global monotonic clock to the application, and that must be shared across all the browser contexts. The global 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 global
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
.Performance
now
()
) at multiple
points within the same context and observe drift between them—e.g. due to
automatic or user clock adjustments. With the
.Performance
attribute, the attacker can also compare the time at which time
origin is zero, as reported by the global monotonic clock,
against the current time-of-day estimate of when it is zero (i.e. the
difference between timeOrigin
Date.now()-performance.now()
and
performance.timeOrigin
) 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.
8. Conformance
As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.
The key words MUST and SHOULD in this document are to be interpreted as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here.
Some conformance requirements are phrased as requirements on attributes, methods or objects. Such requirements are to be interpreted as requirements on user agents.
9. IDL Index
typedef doubleDOMHighResTimeStamp
; [Exposed=(Window,Worker)] interfacePerformance
: EventTarget {DOMHighResTimeStamp
now
(); readonly attributeDOMHighResTimeStamp
timeOrigin
; [Default] objecttoJSON
(); }; partial interface mixinWindowOrWorkerGlobalScope
{ [Replaceable] readonly attributePerformance
performance
; };
A. Acknowledgments
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.
B. References
B.1 Normative references
- [dom]
- DOM Standard. Anne van Kesteren. WHATWG. Living Standard. URL: https://dom.spec.whatwg.org/
- [ECMA-262]
- ECMAScript Language Specification. Ecma International. URL: https://tc39.es/ecma262/
- [HTML]
- HTML Standard. Anne van Kesteren; Domenic Denicola; Ian Hickson; Philip Jägenstedt; Simon Pieters. WHATWG. Living Standard. URL: https://html.spec.whatwg.org/multipage/
- [RFC2119]
- Key words for use in RFCs to Indicate Requirement Levels. S. Bradner. IETF. March 1997. Best Current Practice. URL: https://tools.ietf.org/html/rfc2119
- [RFC8174]
- Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words. B. Leiba. IETF. May 2017. Best Current Practice. URL: https://tools.ietf.org/html/rfc8174
- [SPECTRE]
- Spectre Attacks: Exploiting Speculative Execution. Paul Kocher; Jann Horn; Anders Fogh; Daniel Genkin; Daniel Gruss; Werner Haas; Mike Hamburg; Moritz Lipp; Stefan Mangard; Thomas Prescher; Michael Schwarz; Yuval Yarom. January 2018. URL: https://spectreattack.com/spectre.pdf
- [WEBIDL]
- Web IDL. Boris Zbarsky. W3C. 15 December 2016. W3C Editor's Draft. URL: https://heycam.github.io/webidl/
B.2 Informative references
- [CACHE-ATTACKS]
- The Spy in the Sandbox - Practical Cache Attacks in Javascript. Yossef Oren; Vasileios P. Kemerlis; Simha Sethumadhavan; Angelos D. Keromytis. March 2015. URL: https://arxiv.org/abs/1502.07373
- [HR-TIME-20121217]
- High Resolution Time. Jatinder Mann. W3C. 17 December 2012. W3C Recommendation. URL: https://www.w3.org/TR/2012/REC-hr-time-20121217/
- [PERFORMANCE-TIMELINE-20131212]
- Performance Timeline. Jatinder Mann; Zhiheng Wang. W3C. 12 December 2013. W3C Recommendation. URL: https://www.w3.org/TR/2013/REC-performance-timeline-20131212/