Movatterモバイル変換


[0]ホーム

URL:


This specification defines an interface to help web developers measure the performance of their applications by giving them access to high precision timestamps.

This User Timing specification is intended to supersede [[USER-TIMING-2]] and includes:

Introduction

Web developers need the ability to assess and understand the performance characteristics of their applications. While JavaScript [[ECMA-262]] provides a mechanism to measure application latency (retrieving the current timestamp from theDate.now() method), the precision of this timestamp varies between user agents.

This document defines thePerformanceMark andPerformanceMeasure interfaces, and extensions to thePerformance interface, which expose a high precision, monotonically increasing timestamp so that developers can better measure the performance characteristics of their applications.

The following script shows how a developer can use the interfaces defined in this document to obtain timing data related to developer scripts.

        async function run() {          performance.mark("startTask1");          await doTask1(); // Some developer code          performance.mark("endTask1");          performance.mark("startTask2");          await doTask2(); // Some developer code          performance.mark("endTask2");          // Log them out          const entries = performance.getEntriesByType("mark");          for (const entry of entries) {            console.table(entry.toJSON());          }        }        run();

[[PERFORMANCE-TIMELINE-2]] defines two mechanisms that can be used to retrieve recorded metrics:getEntries() andgetEntriesByType() methods, and thePerformanceObserver interface. The former is best suited for cases where you want to retrieve a particular metric by name at a single point in time, and the latter is optimized for cases where you may want to receive notifications of new metrics as they become available.

As another example, suppose that there is an element which, when clicked, fetches some new content and indicates that it has been fetched. We'd like to report the time from when the user clicked to when the fetch was complete. We can't mark the time the click handler executes since that will miss latency to process the event, so instead we use the event hardware timestamp. We also want to know the name of the component to have more detailed analytics.

        element.addEventListener("click", e => {          const component = getComponent(element);          fetch(component.url).then(() => {            element.textContent = "Updated";            const updateMark = performance.mark("update_component", {              detail: {component: component.name},            });            performance.measure("click_to_update_component", {              detail: {component: component.name},              start: e.timeStamp,              end: updateMark.startTime,            });          });        });

Some conformance requirements are phrased as requirements on attributes, methods or objects. Such requirements are to be interpreted as requirements on user agents.

The IDL fragments in this specification MUST be interpreted as required for conforming IDL fragments, as described in the Web IDL specification. [[WEBIDL]]

User Timing

Extensions to thePerformance interface

ThePerformance interface andDOMHighResTimeStamp are defined in [[HR-TIME-2]]. ThePerformanceEntry interface is defined in [[PERFORMANCE-TIMELINE-2]].

        dictionary PerformanceMarkOptions {            any detail;            DOMHighResTimeStamp startTime;        };        dictionary PerformanceMeasureOptions {            any detail;            (DOMString or DOMHighResTimeStamp) start;            DOMHighResTimeStamp duration;            (DOMString or DOMHighResTimeStamp) end;        };        partial interface Performance {            PerformanceMark mark(DOMString markName, optional PerformanceMarkOptions markOptions = {});            undefined clearMarks(optional DOMString markName);            PerformanceMeasure measure(DOMString measureName, optional (DOMString or PerformanceMeasureOptions) startOrMeasureOptions = {}, optional DOMString endMark);            undefined clearMeasures(optional DOMString measureName);        };

mark() method

Stores a timestamp with the associated name (a "mark"). It MUST run these steps:

  1. Run thePerformanceMark constructor and letentry be the newly created object.
  2. Queueentry.
  3. Addentry to theperformance entry buffer.
  4. Returnentry.

PerformanceMarkOptions dictionary

detail
Metadata to be included in the mark.
startTime
Timestamp to be used as the mark time.

clearMarks() method

Removes the stored timestamp with the associated name. It MUST run these steps:

  1. IfmarkName is omitted, remove allPerformanceMark objects from theperformance entry buffer.
  2. Otherwise, remove allPerformanceMark objects listed in theperformance entry buffer whosename [=string/is=]markName.
  3. Returnundefined.

measure() method

Stores the {{DOMHighResTimeStamp}} duration between two marks along with the associated name (a "measure"). It MUST run these steps:

  1. IfstartOrMeasureOptions is aPerformanceMeasureOptions object and at least one ofstart,end,duration, anddetail [=map/exist=], run the following checks:
    1. IfendMark is given,throw aTypeError.
    2. IfstartOrMeasureOptions'sstart andend members are both omitted,throw aTypeError.
    3. IfstartOrMeasureOptions'sstart,duration, andend members all [=map/exist=],throw aTypeError.
  2. Computeend time as follows:
    1. IfendMark is given, letend time be the value returned by running theconvert a mark to a timestamp algorithm passing inendMark.
    2. Otherwise, ifstartOrMeasureOptions is aPerformanceMeasureOptions object, and if itsend member [=map/exists=], letend time be the value returned by running theconvert a mark to a timestamp algorithm passing instartOrMeasureOptions'send.
    3. Otherwise, ifstartOrMeasureOptions is aPerformanceMeasureOptions object, and if itsstart andduration members both [=map/exist=]:
      1. Letstart be the value returned by running theconvert a mark to a timestamp algorithm passing instart.
      2. Letduration be the value returned by running theconvert a mark to a timestamp algorithm passing induration.
      3. Letend time bestart plusduration.
    4. Otherwise, letend time be the value that would be returned by thePerformance object'snow() method.
  3. Computestart time as follows:
    1. IfstartOrMeasureOptions is aPerformanceMeasureOptions object, and if itsstart member [=map/exists=], letstart time be the value returned by running theconvert a mark to a timestamp algorithm passing instartOrMeasureOptions'sstart.
    2. Otherwise, ifstartOrMeasureOptions is aPerformanceMeasureOptions object, and if itsduration andend members both [=map/exist=]:
      1. Letduration be the value returned by running theconvert a mark to a timestamp algorithm passing induration.
      2. Letend be the value returned by running theconvert a mark to a timestamp algorithm passing inend.
      3. Letstart time beend minusduration.
    3. Otherwise, ifstartOrMeasureOptions is aDOMString, letstart time be the value returned by running theconvert a mark to a timestamp algorithm passing instartOrMeasureOptions.
    4. Otherwise, letstart time be0.
  4. Create a newPerformanceMeasure object (entry) withthis'srelevant realm.
  5. Setentry'sname attribute tomeasureName.
  6. Setentry'sentryType attribute toDOMString "measure".
  7. Setentry'sstartTime attribute tostart time.
  8. Setentry'sduration attribute to the duration fromstart time toend time. The resulting duration value MAY be negative.
  9. Setentry'sdetail attribute as follows:
    1. IfstartOrMeasureOptions is aPerformanceMeasureOptions object andstartOrMeasureOptions'sdetail member [=map/exists=]:
      1. Letrecord be the result of calling theStructuredSerialize algorithm onstartOrMeasureOptions'sdetail.
      2. Setentry'sdetail to the result of calling theStructuredDeserialize algorithm onrecord and thecurrent realm.
    2. Otherwise, set it tonull.
  10. Queueentry.
  11. Addentry to theperformance entry buffer.
  12. Returnentry.

PerformanceMeasureOptions dictionary

detail
Metadata to be included in the measure.
start
Timestamp to be used as the start time or string to be used as start mark.
duration
Duration between the start and end times.
end
Timestamp to be used as the end time or string to be used as end mark.

clearMeasures() method

Removes stored timestamp with the associated name. It MUST run these steps:

  1. IfmeasureName is omitted, remove allPerformanceMeasure objects in theperformance entry buffer.
  2. Otherwise remove allPerformanceMeasure objects listed in theperformance entry buffer whosename [=string/is=]measureName.
  3. Returnundefined.

ThePerformanceMark Interface

ThePerformanceMark interface also exposes marks created via the {{Performance}} interface's {{Performance/mark()}} method to thePerformance Timeline.

        [Exposed=(Window,Worker)]        interface PerformanceMark : PerformanceEntry {          constructor(DOMString markName, optional PerformanceMarkOptions markOptions = {});          readonly attribute any detail;        };

ThePerformanceMark interface extends the following attributes of the {{PerformanceEntry}} interface:

Thename attribute must return the mark's name.

TheentryType attribute must return theDOMString"mark".

ThestartTime attribute must return a {{DOMHighResTimeStamp}} with the mark's time value.

Theduration attribute must return a {{DOMHighResTimeStamp}} of value0.

ThePerformanceMark interface contains the following additional attribute:

Thedetail attribute must return the value it is set to (it's copied from thePerformanceMarkOptions dictionary).

ThePerformanceMark Constructor

ThePerformanceMark constructor must run the following steps:

  1. If thecurrent global object is aWindow object andmarkName uses the same name as aread only attribute in thePerformanceTiming interface,throw aSyntaxError.
  2. Create a newPerformanceMark object (entry) with thecurrent global object'srealm.
  3. Setentry'sname attribute tomarkName.
  4. Setentry'sentryType attribute toDOMString "mark".
  5. Setentry'sstartTime attribute as follows:
    1. IfmarkOptions'sstartTime member [=map/exists=], then:
      1. IfmarkOptions'sstartTime is negative, throw aTypeError.
      2. Otherwise, setentry'sstartTime to the value ofmarkOptions'sstartTime.
    2. Otherwise, set it to the value that would be returned by thePerformance object'snow() method.
  6. Setentry'sduration attribute to0.
  7. IfmarkOptions'sdetail is null, setentry'sdetail to null.
  8. Otherwise:
    1. Letrecord be the result of calling theStructuredSerialize algorithm onmarkOptions'sdetail.
    2. Setentry'sdetail to the result of calling theStructuredDeserialize algorithm onrecord and thecurrent realm.

ThePerformanceMeasure Interface

ThePerformanceMeasure interface also exposes measures created via the {{Performance}} interface's {{Performance/measure()}} method to thePerformance Timeline.

        [Exposed=(Window,Worker)]        interface PerformanceMeasure : PerformanceEntry {          readonly attribute any detail;        };

ThePerformanceMeasure interface extends the following attributes of the {{PerformanceEntry}} interface:

Thename attribute must return the measure's name.

TheentryType attribute must return theDOMString"measure".

ThestartTime attribute must return a {{DOMHighResTimeStamp}} with the measure's start mark.

Theduration attribute must return a {{DOMHighResTimeStamp}} with the duration of the measure.

ThePerformanceMeasure interface contains the following additional attribute:

Thedetail attribute must return the value it is set to (it's copied from thePerformanceMeasureOptions dictionary).

Processing

A user agent implementing the User Timing API would need to include"mark" and"measure" in supportedEntryTypes. This allows developers to detect support for User Timing.

Convert amark to atimestamp

Toconvert a mark to a timestamp, given amark that is aDOMString or {{DOMHighResTimeStamp}} run these steps:

  1. Ifmark is aDOMString and it has the same name as aread only attribute in thePerformanceTiming interface, letend time be the value returned by running theconvert a name to a timestamp algorithm withname set to the value ofmark.
  2. Otherwise, ifmark is aDOMString, letend time be the value of thestartTime attribute from the most recent occurrence of aPerformanceMark object in theperformance entry buffer whosename [=string/is=]mark. If no matching entry is found,throw aSyntaxError.
  3. Otherwise, ifmark is a {{DOMHighResTimeStamp}}:
    1. Ifmark is negative, throw aTypeError.
    2. Otherwise, letend time bemark.

Convert aname to atimestamp

Toconvert a name to atimestamp given aname that is aread only attribute in thePerformanceTiming interface, run these steps:

  1. If theglobal object is not aWindow object,throw aTypeError.
  2. Ifname isnavigationStart, return0.
  3. LetstartTime be the value ofnavigationStart in thePerformanceTiming interface.
  4. LetendTime be the value ofname in thePerformanceTiming interface.
  5. IfendTime is0,throw anInvalidAccessError.
  6. Return result of subtractingstartTime fromendTime.

ThePerformanceTiming interface was defined in [[NAVIGATION-TIMING]] and is now considered obsolete. The use of names from thePerformanceTiming interface is supported to remain backwards compatible, but there are no plans to extend this functionality to names in thePerformanceNavigationTiming interface defined in [[NAVIGATION-TIMING-2]] (or other interfaces) in the future.

Recommended mark names

Developers are encouraged to use the following recommended mark names to mark common timings. Theuser agent does not validate that the usage of these names is appropriate or consistent with its description.

Adding such recommended mark names can help performance tools tailor guidance to a site. These mark names can also help real user monitoring providers and user agents collect web developer signals regarding their application's performance at scale, and surface this information to developers without requiring any site-specific work.

"mark_fully_loaded"
The time when the page is considered fully loaded as marked by the developer in their application.

In this example, the page asynchonously initializes a chat widget, a searchbox, and a newsfeed upon loading. When finished, the "mark_fully_loaded" mark name enables lab tools and analytics providers to automatically show the timing.

                window.addEventListener("load", (event) => {                  Promise.all([                    loadChatWidget(),                    initializeSearchAutocomplete(),                    initializeNewsfeed()]).then(() => {                      performance.mark('mark_fully_loaded');                  });                });
"mark_fully_visible"
The time when the page is considered fully visible to an end-user as marked by the developer in their application.
"mark_interactive"
The time when the page is considered interactive to an end-user as marked by the developer in their application.
"mark_feature_usage"
Mark the usage of a feature which may impact performance so that tooling and analytics can take it into account. Thedetail metadata can contain any useful information about the feature, including:
feature
The name of the feature used.
framework
If applicable, the underlying framework the feature is intended for, such as a JavaScript framework, content management system, or e-commerce platform.

In this example, the ImageOptimizationComponent for FancyJavaScriptFramework is used to size images for optimal performance. The code notes this feature's usage so that lab tools and analytics can measure whether it helped improve performance.

            performance.mark('mark_feature_usage', {              'detail': {                'feature': 'ImageOptimizationComponent',                'framework': 'FancyJavaScriptFramework'              }            })

Privacy and Security

The interfaces defined in this specification expose potentially sensitive timing information on specific JavaScript activity of a page. Please refer to [[HR-TIME-2]] for privacy and security considerations of exposing high-resolution timing information.

Because the web platform has been designed with the invariant that any script included on a page has the same access as any other script included on the same page, regardless of the origin of either scripts, the interfaces defined by this specification do not place any restrictions on recording or retrieval of recorded timing information - i.e. a user timing mark or measure recorded by any script included on the page can be read by any other script running on the same page, regardless of origin.

Acknowledgments

Thanks to James Simonsen, Jason Weber, Nic Jansma, Philippe Le Hegaret, Karen Anderson, Steve Souders, Sigbjorn Vik, Todd Reifsteck, and Tony Gentilcore for their contributions to this work.


[8]ページ先頭

©2009-2025 Movatter.jp