欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > performance.now() 与 Date.now() 对比

performance.now() 与 Date.now() 对比

2024/10/25 4:14:58 来源:https://blog.csdn.net/sunboylife/article/details/141170619  浏览:    关键词:performance.now() 与 Date.now() 对比

Date.now()

Date.now() 方法返回当前时间与 Unix 时间戳(1970 年 1 月 1 日 00:00:00 UTC)之间的时间差,单位是毫秒。

特性

时间基点:从 Unix 时间戳到当前时间。
精度:依赖于系统的时钟分辨率,通常在 1 至 15 毫秒之间。
用途:适合用于记录日期和时间,例如记录用户的操作时间或计算两个日期之间的差异。

示例:

const currentTime = Date.now();
console.log(currentTime);

performance.now()

performance.now() 方法返回一个高分辨率的时间戳,这个时间戳表示自某个固定的起始点以来所经过的时间(通常是页面加载开始的时间)。
performance.now是浏览器(Web API)提供的方法,不同浏览器获取到的精度不同。Date.now是Javascript内置方法,差异主要在于浏览器遵循的ECMAScript规范。
Date.now() ≈ performance.timing.navigationStart + performance.now()

特性

时间基点:从页面加载开始到当前时间。
精度:通常比 Date.now() 提供更高的分辨率,可以达到亚毫秒级(例如 0.001 毫秒)。
用途:适合用于性能监控、计时脚本执行时间、动画和游戏开发中的时间控制等。

示例:

const startTime = performance.now();// 执行一些耗时的操作
function doSomethingExpensive() {// ...
}
doSomethingExpensive();const endTime = performance.now();
const duration = endTime - startTime;
console.log(`The operation took ${duration} milliseconds.`);

详细比较

时间基点
Date.now() 基于 Unix 时间戳(1970 年 1 月 1 日 00:00:00 UTC)。
performance.now() 基于页面加载开始的时间。
精度
Date.now() 受限于系统的时钟分辨率,通常为 15 毫秒左右。
performance.now() 提供更高的精度,通常为亚毫秒级。
用途
Date.now() 通常用于记录确切的时间点,如日期和时间记录。
performance.now() 用于需要高精度计时的场景,如性能测试、游戏开发和动画。
示例
假设我们想要比较一个函数的执行时间:

// 使用 Date.now()
const startTimeDate = Date.now();
// 执行耗时操作
function doSomethingExpensive() {for (let i = 0; i < 1000000000; i++) {}
}
doSomethingExpensive();
const endTimeDate = Date.now();
const durationDate = endTimeDate - startTimeDate;
console.log(`Duration with Date.now(): ${durationDate} ms`);// 使用 performance.now()
const startTimePerformance = performance.now();
doSomethingExpensive();
const endTimePerformance = performance.now();
const durationPerformance = endTimePerformance - startTimePerformance;
console.log(`Duration with performance.now(): ${durationPerformance.toFixed(3)} ms`);

在这个例子中,你会看到 performance.now() 提供了更准确的时间间隔,而 Date.now() 的结果可能不够精确。

总结来说,如果你需要记录确切的时间点或者计算两个时间点之间的差异,使用 Date.now();如果你需要进行精确的时间测量,例如计时函数的执行时间,那么使用 performance.now()。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com