我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
当前回答
要启动计时器,请使用console.time(“myTimer”);可选:要打印经过的时间,请使用console.timeLog(“myTimer”);最后,停止计时器并打印最终结果time:console.timeEnd(“myTimer”);
您可以在MDN和Node.js文档中阅读更多关于这一点的信息。
可在Chrome、Firefox、Opera和NodeJS上使用。(不在Edge或Internet Explorer上)。
其他回答
不要使用Date()。阅读以下内容。
使用performance.now():
<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>
它适用于:
即10++火狐15++铬24++Safari 8++歌剧15++Android 4.4++等等
console.time对你来说可能可行,但它是非标准的§:
此功能是非标准的,不在标准轨道上。不要在面向Web的生产网站上使用它:它不会对每个用户都有效。实现之间也可能存在很大的不兼容性,并且行为可能会在未来发生变化。
除了浏览器支持之外,performance.now似乎有可能提供更准确的计时,因为它似乎是console.time的基本版本。
<rant>此外,不要将Date用于任何事情,因为它会受到“系统时间”变化的影响。这意味着当用户没有准确的系统时间时,我们将得到无效的结果,如“负计时”:
2014年10月,我的系统时钟失控了,猜猜怎么了。。。。我打开Gmail,看到我一天的所有电子邮件都是“0分钟前发送的”。我还以为Gmail应该是由谷歌的世界级工程师建造的。。。。。。。
(将你的系统时钟设置为一年前,然后转到Gmail,这样我们都可以开怀大笑。也许有一天,我们会为JS Date举办一个“耻辱大厅”。)
Google Spreadsheet的now()函数也存在此问题。
您将使用Date的唯一时间是您想向用户显示其系统时钟时间的时间。当你想得到时间或测量任何东西时,就不会这样。
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(标签);//返回初始化和结束之间的总时间
要获得精确的值,您应该使用Performance接口。Firefox、Chrome、Opera和IE的现代版本都支持它。下面是如何使用它的示例:
var performance = window.performance;
var t0 = performance.now();
doWork();
var t1 = performance.now();
console.log("Call to doWork took " + (t1 - t0) + " milliseconds.")
Date.getTime()或console.time()不适合测量精确的执行时间。如果快速粗略估计对您来说合适,您可以使用它们。粗略估计,我的意思是你可以从实时得到15-60毫秒的偏移。
查看这篇关于测量JavaScript执行时间的精彩文章。作者还提供了一些关于JavaScript时间准确性的链接,值得一读。
下面是计时函数的修饰符
它包装函数,以便它们每次运行时都能计时
用法:
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,这应该适用于这些函数。如果您希望一个装饰器同时处理同步和异步函数,则会变得更加复杂。
几个月前,我用Date.now()编写了自己的例程,对函数进行计时——尽管当时接受的方法似乎是performance.now(--因为性能对象在稳定的Node.js版本中还不可用(内置)。
今天我做了更多的研究,发现了另一种计时方法。由于我还发现了如何在Node.js代码中使用它,所以我想在这里分享一下。
以下内容结合了w3c和Node.js给出的示例:
function functionTimer() {
performance.mark('start')
functionToBeTimed()
performance.mark('end')
performance.measure('Start to End', 'start', 'end')
const measure = performance.getEntriesByName('Start to End')[0]
console.log(measure.duration)
}
注:
如果您打算在Node.js应用程序中使用性能对象,则必须包含以下要求:const{performance}=require('perf_hooks')