我可以轻松地做到这一点:
console.time('mytimer');
doSomeWork();
console.timeEnd('mytimer');
但是是否可以在多个函数中计算时间。我需要在全局变量中定义脚本的开始时间。然后在多个函数中,我将写下自时间开始以来经过了多少毫秒。并写出函数的名称,如下所示:
console.time('mytimer');
doSomeWork() {
// console.log(difference between now and "mytimer"s start time)
// console.log(name of the function: doSomeWork())
};
doSomeWork2() {
// console.log(difference between now and "mytimer"s start time)
// console.log(name of the function: doSomeWork2())
};
doSomeWork3() {
// console.log(difference between now and "mytimer"s start time)
// console.log(name of the function: doSomeWork3())
};
console.timeEnd('mytimer');
我将在 Chrome 26+ 中使用它来解决调试问题,因此使用浏览器相关函数(例如:arguments.callee.name)不是问题。
编辑:为了解决我的问题。
这有效:
console.time('myTimer1');
console.timeEnd('myTimer1');
这不起作用:
console.time('myTimer2');
console.time('myTimer2');
编辑:当然,可以编写太多计时器并检查每个计时器的时间。但我需要知道自从 JavaScript 代码在每一圈启动以来经过的时间。
如果您需要特定功能的时间,我想您知道它们可以通过 console.time() 和 console.timeEnd() 的参数来实现。有关它的更多信息请点击此处https://developers.google.com/chrome-developer-tools/docs/console/ https://developers.google.com/chrome-developer-tools/docs/console/ .
根据我对你问题的理解,你需要几圈来进行基准分析。
我定义了以下方法,您可以使用它们来获取以毫秒为单位的单圈时间。
Update: 使用表现 https://developer.mozilla.org/en-US/docs/Web/API/Performance/nowapi 是此类用例的推荐 API。
console.lapStart = function(name){
window[name] = window[name] || {};
window[name].globalTimer = performance.now();
}
console.showLap = function(name){
currTime = performance.now();
var diff = currTime - window[name].globalTimer;
console.log(arguments.callee.name, diff);
}
console.lapEnd = function(name){
currTime = performance.now();
var diff = currTime - window[name].globalTimer;
console.log(arguments.callee.name, diff);
delete window[name]
}
请注意,这是粗略的代码,只能在开发中运行。否则,它可能会在全局对象中留下不好的痕迹,并在你的嘴里留下不好的味道。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)