1.通过new Date()
const beginTime = +new Date()
fn()
const endTime = +new Date()
console.log(`fn()所用的时间大约为: ${(endTime - beginTime)}ms`)
2.通过console.time()
const str = 'fn take long'
console.time(str)
fn()
console.timeEnd(str)
3.定义函数,并测试代码
function fn () {
const arr = Array.from({length: 10000})
let count = 0
arr.forEach(num => {
conut += num
})
}
4.测试结果
fn()所用的时间等于: 1ms
fn take long: 0.97216796875 ms