这是异步函数的简单包装计时函数:
// async function execution time wrapper
async function fnTime(fn, ...params) {
const start = process.hrtime()
const result = await fn(...params)
const end = process.hrtime(start)
console.log(
`[${fn.name}] Execution time:${(end[0] * 1000000000 + end[1]) /
1000000} ms`
)
return result
}
示例用法(请参阅repl.it上的此演示):
// usage
const setTimeoutPromise = ms => new Promise(resolve => setTimeout(resolve, ms))
// example 2:
// get name from db
const db = {
async getUser(id){
// simulate wait for record retrival from db
await fnTime(setTimeoutPromise, 150)
return {
_id: id,
name: 'John Doe',
organisation: 'UN',
email: 'johndoe@un.org'
}
}
}
// test it
;(async function(){
const result = await fnTime(db.getUser, 'asfa98th4nfwef0qwrwef0')
console.log('result', result)
})()
// result:
// [setTimeoutPromise] Execution time:197.928094 ms
// [getUser] Execution time:199.480553 ms