A fundamental requirement of web performance is a precise and consistent definition of time. DOMHighResTimeStamp type (a double ) is used by all performance interfaces to hold such time values. Additionally, there must be a way to create a timestamp for a specific point in time; this is done with the now() 方法。

Web performance interfaces are defined in a suite of standards base interface for these standards is the 性能 interface and its methods and properties are extended by different standards. This guide describes how to use the 性能 interfaces that are defined in the High-Resolution Time standard. Other web performance guides (listed in the 另请参阅 section) describe how to use additional methods and properties of the 性能 接口。

High precision timing

High precision timing is achieved by using the DOMHighResTimeStamp type for time values. The unit is milliseconds and should be accurate to 5 µs (microseconds). However, if the browser is unable to provide a time value accurate to 5 microseconds (because of hardware or software constraints, for example), the browser can represent the value as a time in milliseconds accurate to a millisecond.

The following code example shows the use of DOMHighResTimeStamp Performance.now() 方法。 now() 方法返回 timestamp (of type DOMHighResTimeStamp ) that is a discrete point in time. By calling this method before and after a task, the time it takes to do the task can be measured.

function calculate_time() {
  var startTime;
  var endTime;
  startTime = performance.now();
  do_task();
  endTime = performance.now();
  return (endTime - startTime);
}
					

Serializing the 性能 对象

JSON serialization of the 性能 object is done via the toJSON() method. In the following example, JSON serialization for the 性能 , Performance.timing and Performance.navigation objects is printed in the 对象 元素。

function print_json() {
  var json;
  var o = document.getElementsByTagName("output")[0];
  if (window.performance.toJSON === undefined) {
    json = "window.performance.toJSON() is NOT supported";
    o.innerHTML += json + "<br>";
  } else {
    var s;
    json = window.performance.toJSON();
    // Print the performance object
    s = JSON.stringify(json);
    o.innerHTML = "<p>performance = " + s + "</p>";
    // Print the performance.timing and performance.navigation objects
    var perf = JSON.parse(s);
    var timing = perf.timing;
    o.innerHTML += "<p>peformance.timing = " + JSON.stringify(timing) + "</p>";
    var navigation = perf.navigation;
    o.innerHTML += "<p>peformance.navigation = " + JSON.stringify(navigation) + "</p>";
  }
}
					

规范

The interfaces described in this document are defined in the 高分辨率时间 standard which has two levels:

互操作性

As shown in the 性能 接口的 浏览器兼容性 table, most of the 性能 interfaces are broadly implemented by desktop browsers.

另请参阅

元数据

  • 最后修改: