我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
当前回答
注意:纯函数ES6方法的最简单实现,无需额外变量,只需3行代码。处理同步和异步代码,因此不需要外部库,可以在JavaScript和NodeJS中工作,甚至可以用来测试API的延迟
// Create one-liner timer function
let [timer, timingMonitor] = [0, () => timer = !timer ? Date.now() : `${Date.now() - timer}ms`]
// Initiate timer
timingMonitor();
// Your code here
doSomething();
// Capture and store the elapsed time
const timeElapsed = timingMonitor();
console.log(timeElapsed);
// Console output: "102ms", for example
其他回答
下面是计时函数的修饰符
它包装函数,以便它们每次运行时都能计时
用法:
let test = () => { /* does something */ }
test = timed(test) // turns the function into a timed function in one line
test() // run your code as normal, logs 'function test took 1001.900ms'
这是装饰者:
let timed = (f) => (...args) => {
let start = performance.now();
let ret = f(...args);
console.log(`function ${f.name} took ${(performance.now() - start).toFixed(3)}ms`);
return ret;
}
如果您使用的是异步函数,您可以将其设置为定时异步,并在f(…args)之前添加一个await,这应该适用于这些函数。如果您希望一个装饰器同时处理同步和异步函数,则会变得更加复杂。
使用performance.now():
var startTime = performance.now()
doSomething() // <---- measured code goes between startTime and endTime
var endTime = performance.now()
console.log(`Call to doSomething took ${endTime - startTime} milliseconds`)
在Node.js中,需要导入性能类
进口性能
const { performance } = require('perf_hooks');
使用console.time:(生活水平)
console.time('doSomething')
doSomething() // <---- The function you're measuring time for
console.timeEnd('doSomething')
注意:传递给time()和timeEnd()方法的字符串必须匹配(计时器才能按预期完成)。
console.time()文档:MDN文档Node.js文档
要启动计时器,请使用console.time(“myTimer”);可选:要打印经过的时间,请使用console.timeLog(“myTimer”);最后,停止计时器并打印最终结果time:console.timeEnd(“myTimer”);
您可以在MDN和Node.js文档中阅读更多关于这一点的信息。
可在Chrome、Firefox、Opera和NodeJS上使用。(不在Edge或Internet Explorer上)。
export default class Singleton {
static myInstance: Singleton = null;
_timers: any = {};
/**
* @returns {Singleton}
*/
static getInstance() {
if (Singleton.myInstance == null) {
Singleton.myInstance = new Singleton();
}
return this.myInstance;
}
initTime(label: string) {
this._timers[label] = Date.now();
return this._timers[label];
}
endTime(label: string) {
const endTime = Date.now();
if (this._timers[label]) {
const delta = endTime - this._timers[label];
const finalTime = `${label}: ${delta}ms`;
delete this._timers[label];
return finalTime;
} else {
return null;
}
}
}
与字符串相关的InitTime。
return Singleton.getInstance().initTime(标签);//返回时间init
return Singleton.getInstance().endTime(标签);//返回初始化和结束之间的总时间
这是一个计时器功能。如果要测量未嵌套的多个对象之间的时间:
function timer(lap){
if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
timer.prev = performance.now();
}
类似于console.time(),但如果不需要跟踪以前的计时器,则更容易使用。
用法:
timer() // set the start
// do something
timer('built') // logs 'built in: 591.815ms'
// do something
timer('copied') // logs 'copied in: 0.065ms'
// do something
timer('compared') // logs 'compared in: 36.41ms'
如果您喜欢console.time()中的蓝色,可以使用这行
console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');