performance.now()和Date.now()的区别

2,021 阅读1分钟

标准不同

performance.now是浏览器(Web API)提供的方法,不同浏览器获取到的精度不同。Date.now是Javascript内置方法,差异主要在于浏览器遵循的ECMAScript规范。

精度不同

Date.now()

Date.now() 方法返回自 1970 年 1 月 1 日 00:00:00 (UTC) 到当前时间的毫秒数。

performance.now()

performance.now() 方法返回一个精确到毫秒的时间戳,个别浏览器返回的时间戳没有被限制在一毫秒的精确度内,以浮点数的形式表示时间,精度最高可达微秒级,因此测试时如果需要比毫秒更高的精度,可以使用这个方法。

示例(以chrome为例)

const t1 = performance.now()
// 538253.3999999762
const t2 = Date.now()
// 1664162107633

Date.now() ≈ performance.timing.navigationStart + performance.now()

const t1 = performance.timing.navigationStart + performance.now()
const t2 = Date.now();
console.log(t2, t1);
// 1664162454515 1664162454515.9

备注

1秒=1e3毫秒=1e6微秒=1e−12皮秒=1e−15飞秒