我需要以毫秒为单位获得执行时间。
我最初在2008年提出了这个问题。当时被接受的答案是使用
new Date().getTime()
。然而,现在我们都同意使用标准的performance.now()
API更加合适。因此,我将接受的答案更改为这个答案。
我需要以毫秒为单位获得执行时间。
我最初在2008年提出了这个问题。当时被接受的答案是使用
new Date().getTime()
。然而,现在我们都同意使用标准的performance.now()
API更加合适。因此,我将接受的答案更改为这个答案。
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]');
};
基准测试
var stopwatch = new StopWatch();
stopwatch.start();
for (var index = 0; index < 100; index++) {
stopwatch.printElapsed('Instance[' + index + ']');
}
stopwatch.stop();
stopwatch.printElapsed();
输出
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]
performance.now()是可选的 - 只需在StopWatch构造函数中传递false参数即可。
有多种方法可以实现这个目标:
using 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');
this is the most efficient way : using performance.now(), e.g.
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");
use +(add operator) or 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);
当您对日期实例应用一元加操作符时,会发生以下情况: 获取相关日期实例的值 将其转换为数字
注意:getTime()
比一元加操作符具有更好的性能。
为了进一步扩展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;
};
现在像这样使用代码:console.time('someFunction timer');
someFunction();
var executionTime = console.timeEndValue('someFunction timer');
console.log("The execution time is " + executionTime);
这样做会给你带来更多的可能性。你可以将执行时间存储起来,以便将来用于诸如方程计算、存储在数据库中、通过WebSockets发送到远程客户端、提供在网页上等多种用途。
这可能会对你有所帮助。
var t0 = Date.now();
做一些事情();
var t1 = Date.now();
console.log("调用doSomething花费了约" + (t1 - t0)/1000 + "秒。")
这是一个计时器函数。如果您想测量不嵌套的多个事物之间的时间:
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');
performance
:const { performance } = require('perf_hooks');
- Daniel Habenicht使用此代码格式。
const startTime =new Date().getTime();
//do something
const endTime = new Date().getTime();
console.log(`time taken ${(endTime - startTime)/1000} seconds`);
由于某些主要浏览器(如IE10)不支持console.time
和performance.now
,因此我创建了一个轻巧的实用程序,利用了最佳可用方法。但是,它缺乏错误处理功能,无法处理错误的用法(对未初始化的计时器调用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);
}
}
}
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应用程序中使用performance
对象,则必须包括以下要求:
const { performance } = require('perf_hooks')
performance.mark('end')
。 - kofifus感谢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
console.log
也需要时间来执行,并会影响性能测试)。var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
。例如,var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
});
在性能方面
NodeJs: 需要导入performance类
var time0 = performance.now(); // Store the time at this point into time0
yourFunction(); // The function you're measuring time for
var time1 = performance.now(); // Store the time at this point into time1
console.log("youFunction took " + (time1 - time0) + " milliseconds to execute");
使用 console.time
console.time('someFunction');
someFunction(); // Whatever is timed goes between the two "console.time"
console.timeEnd('someFunction');
performance.now()
在 Node 中无法使用。你可以使用new Date().getTime()
来代替,在 Node 中它能正常工作。 - Ryan WalkerDate.now()
,在node中也可以工作。 - f278f1b2