測量應(yīng)用程序中的某個片段需要多長時間是很重要的。
在前端中,我們有 Navigation TimingAPI,Resource Timing API 以及 User Timing API 收集精確的指標(biāo)。
此外厅缺,我們最常用的應(yīng)該是使用 Date
對象來評估某件事情需要多長時間。例如:
const before = Date.now()
console.log(before) // 1505722233092
// some code here
// ...
console.log(Date.now() - before) // 81736ms
我可以用 Date.now
來計算時間宴偿。它返回一個 UNIX 時間戳湘捎。
注意:
Date.now()
方法返回自1970年1月1日UTC 00:00:00以來經(jīng)過的毫秒數(shù)。
console.time
和 console.timeEnd
也是一種很常用的簡便方法窄刘。在你不需要高分辨率計時的情況下窥妇,該測量時間的方式也是一種不錯的選擇。
console.time('testStart')
// some code here
// ...
console.timeEnd('testEnd') // testTime: 48.5732421875 ms
但如果我們想更精確一點呢都哭?
瀏覽器中更精確的時間戳
在瀏覽器中秩伞,我們可以使用 window.performance.now()
方法,其返回一個精確到毫秒的 DOMHighResTimeStamp
欺矫。
window.performance.now
也可用于 Web 或 Services Workers纱新。在 Window 上下文中,返回的值是自 navigationStart
以來經(jīng)過的時間穆趴。
const before = window.performance.now()
console.log(before) // 1381822.74
// some code here
// ...
console.log(window.performance.now() - before) // 7335.410000000149ms
既然脸爱,我們說到了瀏覽器,那我們也應(yīng)該來說一說 Node.js未妹,其有什么方法可以用來測量時間簿废?
Node.js 中更精確的時間戳
Node.js process
模塊中有一個名為 hrtime.bigint()
的方法以毫微秒為單位返回當(dāng)前高分辨率實時值作為 bigint
。
與 process.hrtime()
方法不同络它,它不支持額外的時間參數(shù)族檬,因為差可以通過兩個 bigint
的減法直接計算。
注意:以前是直接使用的
hrtime
化戳,詳細(xì)描述可查看 Node.js 文檔单料。
以下是文檔給出的一個代碼示例:
import { hrtime } from 'process'
const start = hrtime.bigint() // 191051479007711n
setTimeout(() => {
const end = hrtime.bigint() // 191052633396993n
console.log(`Benchmark took ${end - start} nanoseconds`) // 基準(zhǔn)測試耗時 1154389282 毫微秒
}, 1000)
盡可能精確地測量
為了方便起見,我們可以使用一些庫來更加精準(zhǔn)的測量我們的程序花費的多少時間:
hrtime 是通用時間度量 API(Node 和瀏覽器)的簡便封裝器点楼。在 Node 上使用
process.hrtime()
扫尖,瀏覽器中的 performance API,如果兩者都不可用掠廓,則返回到Date
换怖。
默認(rèn)情況下,時間以毫秒為單位:
import hirestime from 'hirestime'
// 時間測量的起始點
const getElapsed = hirestime()
setTimeout(_ => {
// 返回經(jīng)過的毫秒數(shù)
console.log(getElapsed())
}, 1000)
指定單位:
import hirestime from 'hirestime'
// 時間測量的起始點
const getElapsed = hirestime()
setTimeout(_ => {
// 返回經(jīng)過的秒數(shù)
console.log(getElapsed.s())
console.log(getElapsed.seconds())
// 返回經(jīng)過的毫秒數(shù)
console.log(getElapsed.ms())
console.log(getElapsed.milliseconds())
// 返回經(jīng)過的納秒數(shù)
console.log(getElapsed.ns())
console.log(getElapsed.nanoseconds())
}, 1000)