[Toc]
console.time()
console.time('time1')
let o = 0
for (let i = 0; i < 10000000; i++) {
o++
}
console.timeEnd('time1')
// time1: 32.739990234375 ms
Date.now()
let timeStart = Date.now()
let o = 0
for (let i = 0; i < 10000000; i++) {
o++
}
let timeEnd = Date.now()
console.log(timeEnd - timeStart)
// 37
- 存在的問題:如果兩個(gè)
Date.now()
之間的代碼執(zhí)行地足夠快,它倆的差值可能為0锹雏。在一些使用夏令時(shí)的國家里糙置,如果代碼執(zhí)行時(shí)系統(tǒng)時(shí)鐘被修改琢蛤,那么差值可能是負(fù)值或者極大值鹰晨。
performance.now()
let timeStart = performance.now()
let o = 0
for (let i = 0; i < 10000000; i++) {
o++
}
let timeEnd = performance.now()
console.log(timeEnd - timeStart)
// 31.800000000745058
- performance.now()可以保證時(shí)間戳的單調(diào)增長。計(jì)時(shí)器從執(zhí)行上下文創(chuàng)建開始計(jì)時(shí)闷畸。