这是我参与8月更文挑战的第4天,活动详情查看:8月更文挑战html
测量应用程序中的某个片断须要多长时间是很重要的。前端
在前端中,咱们有 Navigation TimingAPI,Resource Timing API 以及 User Timing API 收集精确的指标。node
此外,咱们最经常使用的应该是使用 Date
对象来评估某件事情须要多长时间。例如:npm
const before = Date.now()
console.log(before) // 1505722233092
// some code here
// ...
console.log(Date.now() - before) // 81736ms
复制代码
我能够用 Date.now
来计算时间。它返回一个 UNIX 时间戳。api
注意:
Date.now()
方法返回自1970年1月1日UTC 00:00:00以来通过的毫秒数。浏览器
console.time
和 console.timeEnd
也是一种很经常使用的简便方法。在你不须要高分辨率计时的状况下,该测量时间的方式也是一种不错的选择。markdown
console.time('testStart')
// some code here
// ...
console.timeEnd('testEnd') // testTime: 48.5732421875 ms
复制代码
但若是咱们想更精确一点呢?oop
在浏览器中,咱们可使用 window.performance.now()
方法,其返回一个精确到毫秒的 DOMHighResTimeStamp
。post
window.performance.now
也可用于 Web 或 Services Workers。在 Window 上下文中,返回的值是自 navigationStart
以来通过的时间。测试
const before = window.performance.now()
console.log(before) // 1381822.74
// some code here
// ...
console.log(window.performance.now() - before) // 7335.410000000149ms
复制代码
既然,咱们说到了浏览器,那咱们也应该来讲一说 Node.js,其有什么方法能够用来测量时间?
Node.js process
模块中有一个名为 hrtime.bigint()
的方法以毫微秒为单位返回当前高分辨率实时值做为 bigint
。
与 process.hrtime()
方法不一样,它不支持额外的时间参数,由于差能够经过两个 bigint
的减法直接计算。
注意:之前是直接使用的
hrtime
,详细描述可查看 Node.js 文档。
如下是文档给出的一个代码示例:
import { hrtime } from 'process'
const start = hrtime.bigint() // 191051479007711n
setTimeout(() => {
const end = hrtime.bigint() // 191052633396993n
console.log(`Benchmark took ${end - start} nanoseconds`) // 基准测试耗时 1154389282 毫微秒
}, 1000)
复制代码
为了方便起见,咱们可使用一些库来更加精准的测量咱们的程序花费的多少时间:
hrtime 是通用时间度量 API(Node 和浏览器)的简便封装器。在 Node 上使用
process.hrtime()
,浏览器中的 performance API,若是二者都不可用,则返回到Date
。
默认状况下,时间以毫秒为单位:
import hirestime from 'hirestime'
// 时间测量的起始点
const getElapsed = hirestime()
setTimeout(_ => {
// 返回通过的毫秒数
console.log(getElapsed())
}, 1000)
复制代码
指定单位:
import hirestime from 'hirestime'
// 时间测量的起始点
const getElapsed = hirestime()
setTimeout(_ => {
// 返回通过的秒数
console.log(getElapsed.s())
console.log(getElapsed.seconds())
// 返回通过的毫秒数
console.log(getElapsed.ms())
console.log(getElapsed.milliseconds())
// 返回通过的纳秒数
console.log(getElapsed.ns())
console.log(getElapsed.nanoseconds())
}, 1000)
复制代码