Jul*_*s A 1057 javascript profiling
我需要以毫秒为单位获得执行时间.
我最初在2008年问过这个问题.然后,接受的答案是使用新的Date().getTime()但是,我们现在都同意使用标准的performance.now() API更合适.因此,我正在改变对此问题的接受答案.
vsy*_*ync 1569
var t0 = performance.now();
doSomething(); // <---- The function you're measuring time for
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
Run Code Online (Sandbox Code Playgroud)
NodeJs
:需要导入performance
该类
console.time('someFunction');
someFunction(); // Whatever is timed goes between the two "console.time"
console.timeEnd('someFunction');
Run Code Online (Sandbox Code Playgroud)
注意:
传递给time()
和timeEnd()
方法的字符串必须匹配
(使计时器按预期完成).
console.time()
单证:
Owe*_*wen 615
getTime()方法返回自1970年1月1日午夜以来的毫秒数.
恩.
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// do something
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
Run Code Online (Sandbox Code Playgroud)
Pac*_*ier 399
<script>
var a = performance.now();
alert('do something...');
var b = performance.now();
alert('It took ' + (b - a) + ' ms.');
</script>
Run Code Online (Sandbox Code Playgroud)
它适用于:
IE 10 ++
FireFox 15 ++
Chrome 24 ++
Safari 8 ++
Opera 15 ++
Android 4.4 ++
console.time
对你来说可能是可行的,但它是非标准的§:
此功能是非标准功能,不符合标准.不要在面向Web的生产站点上使用它:它不适用于每个用户.有也可能实现之间不兼容大和行为可能会改变未来.
除了浏览器支持,performance.now
似乎有可能提供更准确的时间,因为它似乎是简单的版本console.time
.
<咆哮>此外,永远不要使用Date
了什么,因为它受到在"系统时间"的变化.这意味着当用户没有准确的系统时间时,我们将得到无效结果 - 如"负时间" -
2014年10月,我的系统时钟乱了,猜猜是什么 ....我打开了Gmail,看到了我所有的一天的电子邮件" 0分钟前发送".我认为Gmail应该由Google的世界级工程师构建.......
(将你的系统时钟设置为一年前,然后转到Gmail,这样我们就可以大笑了.也许有一天我们会为JS 提供一个耻辱大厅Date
.)
Google Spreadsheet的now()
功能也受此问题的影响.
您将要使用的唯一时间Date
是您希望向用户显示其系统时钟时间.不是当你想要得到的时间或测量任何东西.
Nic*_*icJ 51
如果需要在本地开发计算机上获得函数执行时间,可以使用浏览器的分析工具或控制台命令,如console.time()
和console.timeEnd()
.
所有现代浏览器都内置了JavaScript分析器.这些分析器应该提供最准确的测量,因为您不必修改现有代码,这可能会影响函数的执行时间.
要分析您的JavaScript:
或者,在您的开发机器上,您可以使用console.time()
和向代码添加检测console.timeEnd()
.这些功能在Firefox11 +,Chrome2 +和IE11 +中受支持,报告您启动/停止的定时器console.time()
. time()
将用户定义的计时器名称作为参数,timeEnd()
然后报告自计时器启动以来的执行时间:
function a() {
console.time("mytimer");
... do stuff ...
var dur = console.timeEnd("myTimer"); // NOTE: dur only works in FF
}
Run Code Online (Sandbox Code Playgroud)
请注意,只有Firefox会返回timeEnd()
通话中的已用时间.其他浏览器只是将结果报告给开发人员控制台:返回值为timeEnd()
undefined.
如果您想在野外获得函数执行时间,则必须检测代码.你有几个选择.您可以通过查询来简单地保存开始和结束时间new Date().getTime()
:
function a() {
var start = new Date().getTime();
... do stuff ...
var end = new Date().getTime();
var dur = end - start;
}
Run Code Online (Sandbox Code Playgroud)
但是,该Date
对象仅具有毫秒级的分辨率,并且会受到任何OS系统时钟更改的影响.在现代浏览器中,有一个更好的选择.
更好的选择是使用高分辨率时间,也就是说window.performance.now()
. 在两个重要方面now()
比传统Date.getTime()
方式更好:
now()
是一个亚毫秒分辨率的双精度,表示自页面导航开始以来的毫秒数.它返回小数中的微秒数(例如,1000.123的值是1秒和123微秒).
now()
是单调增加的.这很重要,因为Date.getTime()
可能会在后续呼叫中向前跳甚至向后跳.值得注意的是,如果OS的系统时间更新(例如原子钟同步),Date.getTime()
也会更新. now()
保证总是单调增加,因此它不受操作系统的系统时间的影响 - 它将始终是挂钟时间(假设你的挂钟不是原子的......).
now()
几乎可以在任何地方使用new Date().getTime()
,+ new Date
和T Date.now()
是.唯一的例外是,Date
与now()
时代不混合,如Date
基于UNIX的时期(自1970年以来的毫秒数),而now()
就是因为你的页面导航开始的毫秒数(所以它会比小得多Date
).
以下是如何使用的示例now()
:
function a() {
var start = window.performance.now();
... do stuff ...
var end = window.performance.now();
var dur = end - start;
}
Run Code Online (Sandbox Code Playgroud)
now()
Chrome stable,Firefox 15+和IE10支持.还有几种填充剂.
用于测量野外执行时间的另一个选项是UserTiming.UserTiming的行为类似于console.time()
和console.timeEnd()
,但它使用相同的高分辨率时间戳now()
(因此您得到一个亚毫秒单调增加的时钟),并将时间戳和持续时间保存到PerformanceTimeline.
UserTiming具有标记(时间戳)和度量(持续时间)的概念.您可以根据需要定义任意数量,并在PerformanceTimeline上公开它们.
要保存时间戳,请致电mark(startMarkName)
.要获得自第一个标记以来的持续时间,您只需致电measure(measurename, startMarkname)
.然后,持续时间将与您的标记一起保存在PerformanceTimeline中.
function a() {
window.performance.mark("start");
... do stuff ...
window.performance.measure("myfunctionduration", "start");
}
// duration is window.performance.getEntriesByName("myfunctionduration", "measure")[0];
Run Code Online (Sandbox Code Playgroud)
UserTiming可在IE10 +和Chrome25 +中使用.还有一个polyfill(我写的).
Var*_*ina 33
要获得精确值,您应该使用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.")
Run Code Online (Sandbox Code Playgroud)
Date.getTime()
或者console.time()
不适合测量精确的执行时间.如果您可以快速粗略估算,则可以使用它们.通过粗略估计,我的意思是你可以从实时转换15-60毫秒.
查看关于在JavaScript中测量执行时间的精彩文章.作者还提供了一些关于JavaScript时间准确性的链接,值得一读.
Ste*_*Mai 18
使用Firebug,启用Console和Javascript.点击个人资料 刷新.再次单击配置文件 查看报告.
Ach*_*ner 12
process.hrtime()在Node.js中可用- 它返回一个以纳秒为单位的值
var hrTime = process.hrtime()
console.log(hrTime[0] * 1000000 + hrTime[1] / 1000)
Run Code Online (Sandbox Code Playgroud)
kay*_*yz1 11
var StopWatch = function (performance) {
this.startTime = 0;
this.stopTime = 0;
this.running = false;
this.performance = performance === false ? false : !!window.performance;
};
StopWatch.prototype.currentTime = function () {
return this.performance ? window.performance.now() : new Date().getTime();
};
StopWatch.prototype.start = function () {
this.startTime = this.currentTime();
this.running = true;
};
StopWatch.prototype.stop = function () {
this.stopTime = this.currentTime();
this.running = false;
};
StopWatch.prototype.getElapsedMilliseconds = function () {
if (this.running) {
this.stopTime = this.currentTime();
}
return this.stopTime - this.startTime;
};
StopWatch.prototype.getElapsedSeconds = function () {
return this.getElapsedMilliseconds() / 1000;
};
StopWatch.prototype.printElapsed = function (name) {
var currentName = name || 'Elapsed:';
console.log(currentName, '[' + this.getElapsedMilliseconds() + 'ms]', '[' + this.getElapsedSeconds() + 's]');
};
Run Code Online (Sandbox Code Playgroud)
基准
var stopwatch = new StopWatch();
stopwatch.start();
for (var index = 0; index < 100; index++) {
stopwatch.printElapsed('Instance[' + index + ']');
}
stopwatch.stop();
stopwatch.printElapsed();
Run Code Online (Sandbox Code Playgroud)
产量
Instance[0] [0ms] [0s]
Instance[1] [2.999999967869371ms] [0.002999999967869371s]
Instance[2] [2.999999967869371ms] [0.002999999967869371s]
/* ... */
Instance[99] [10.999999998603016ms] [0.010999999998603016s]
Elapsed: [10.999999998603016ms] [0.010999999998603016s]
Run Code Online (Sandbox Code Playgroud)
performance.now()是可选的 - 只需将false传递给StopWatch构造函数.
为了进一步扩展vsync的代码以使得能够在NodeJS中返回timeEnd作为值,使用这一小段代码.
console.timeEndValue = function(label) { // Add console.timeEndValue, to add a return value
var time = this._times[label];
if (!time) {
throw new Error('No such label: ' + label);
}
var duration = Date.now() - time;
return duration;
};
Run Code Online (Sandbox Code Playgroud)
现在使用代码如下:
console.time('someFunction timer');
someFunction();
var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);
Run Code Online (Sandbox Code Playgroud)
这为您提供了更多可能性.您可以存储执行时间以用于更多目的,例如在方程式中使用它,或存储在数据库中,通过websockets发送到远程客户端,在网页上提供服务等.
你也可以在这里使用add运算符
var start = +new Date();
callYourFunctionHere();
var end = +new Date();
var time = end - start;
console.log('total execution time = '+ time + 'ms');
Run Code Online (Sandbox Code Playgroud)
这是计时函数的装饰器
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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
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'
Run Code Online (Sandbox Code Playgroud)
如果您使用异步函数,您可以进行timed
异步并await
在 f(...args) 之前添加一个,这应该适用于那些。如果您希望一个装饰器同时处理同步和异步功能,则情况会变得更加复杂。
小智 8
有多种方法可以实现这一目标:
使用 console.time
console.time('function');
//run the function in between these two lines for that you need to
//measure time taken by the function. ("ex. function();")
console.timeEnd('function');
Run Code Online (Sandbox Code Playgroud)这是最有效的方法: 使用 performance.now(),例如
var v1 = performance.now();
//run the function here for which you have top measure the time
var v2 = performance.now();
console.log("total time taken = "+(v2-v1)+"milliseconds");
Run Code Online (Sandbox Code Playgroud)使用 +(add operator) 或 getTime()
var h2 = +new Date(); //or
var h2 = new Date().getTime();
for(i=0;i<500;i++) { /* do something */}
var h3 = +new Date(); //or
var h3 = new Date().getTime();
var timeTaken = h3-h2;
console.log("time ====", timeTaken);
Run Code Online (Sandbox Code Playgroud)以下是将一元加号运算符应用于 Date 实例时发生的情况:获取相关 Date 实例的值将其转换为数字
注意:getTime()
提供比一元 + 运算符更好的性能。
这是一个定时器功能。如果您想测量多个未嵌套的事物之间的时间:
function timer(lap){
if(lap) console.log(`${lap} in: ${(performance.now()-timer.prev).toFixed(3)}ms`);
timer.prev = performance.now();
}
Run Code Online (Sandbox Code Playgroud)
与 类似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'
Run Code Online (Sandbox Code Playgroud)
如果您喜欢 中的蓝色console.time()
,您可以使用此行代替
console.log(`${lap} in: %c${(performance.now()-timer.prev).toFixed(3)}ms`, 'color:blue');
Run Code Online (Sandbox Code Playgroud)
使用此代码格式
const startTime =new Date().getTime();
//do something
const endTime = new Date().getTime();
console.log(`time taken ${(endTime - startTime)/1000} seconds`);
Run Code Online (Sandbox Code Playgroud)
只能使用一个变量:
var timer = -performance.now();
// Do something
timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")
Run Code Online (Sandbox Code Playgroud)
timer/1000
-将毫秒转换为秒
.toFixed(5)
-修剪多余的数字
由于console.time
并且performance.now
在某些主流浏览器(即IE10)中不受支持,我创建了一个利用最佳可用方法的超薄实用程序.但是,它缺少错误处理的错误处理(调用End()
未初始化的计时器).
使用它并根据需要进行改进.
Performance: {
Timer: {},
Start: function (name) {
if (console && console.time) {
console.time(name);
} else if (window.performance.now) {
this.Timer[name] = window.performance.now();
} else {
this.Timer[name] = new Date().getTime();
}
},
End: function (name) {
if (console && console.time) {
console.timeEnd(name);
} else {
var result;
if (window.performance.now) {
result = window.performance.now() - this.Timer[name];
} else {
result = new Date().getTime() - this.Timer[name];
}
console.log(name + ": " + result);
}
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢,Achim Koellner,将扩展您的答案:
var t0 = process.hrtime();
//Start of code to measure
//End of code
var timeInMilliseconds = process.hrtime(t0)[1]/1000000; // dividing by 1000000 gives milliseconds from nanoseconds
Run Code Online (Sandbox Code Playgroud)
请注意,除了要测量的内容外,您不应该做任何事情(例如,console.log
执行也需要时间并会影响性能测试)。
请注意,为了通过测量异步函数的执行时间,您应该var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
在回调中插入。例如,
var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
});
Run Code Online (Sandbox Code Playgroud)
小智 5
它可能会帮助你.
var t0 = date.now();
doSomething();
var t1 = date.now();
console.log("Call to doSomething took approximate" + (t1 - t0)/1000 + " seconds.")
几个月前,我整理了自己的例程,使用 Date.now() 对函数进行计时——尽管当时接受的方法似乎是 Performance.now()——因为性能对象尚不可用(构建-in) 在稳定的 Node.js 版本中。
今天我做了更多研究,发现了另一种计时方法。由于我还发现了如何在 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)
}
Run Code Online (Sandbox Code Playgroud)
笔记:
如果您打算在 Node.js 应用程序中使用该performance
对象,则必须包含以下要求:
const { performance } = require('perf_hooks')
归档时间: |
|
查看次数: |
591371 次 |
最近记录: |