我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
我需要以毫秒为单位获取执行时间。
我最初问这个问题是在2008年。当时接受的答案是使用newDate().getTime()。然而,我们现在都可以同意使用标准performance.now()API更合适。因此,我将接受的答案改为这个答案。
当前回答
具有性能
NodeJs:需要导入性能类
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');
其他回答
注意:纯函数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
要启动计时器,请使用console.time(“myTimer”);可选:要打印经过的时间,请使用console.timeLog(“myTimer”);最后,停止计时器并打印最终结果time:console.timeEnd(“myTimer”);
您可以在MDN和Node.js文档中阅读更多关于这一点的信息。
可在Chrome、Firefox、Opera和NodeJS上使用。(不在Edge或Internet Explorer上)。
只能使用一个变量:
var timer = -performance.now();
// Do something
timer += performance.now();
console.log("Time: " + (timer/1000).toFixed(5) + " sec.")
timer/1000-将毫秒转换为秒
.toFixed(5)-修剪多余的数字
谢谢,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]/10000;在回调中。例如
var t0 = process.hrtime();
someAsyncFunction(function(err, results) {
var timeInMilliseconds = process.hrtime(t0)[1]/1000000;
});
公认的答案是错误的!
由于JavaScript是异步的,因此接受的答案的变量端的值将是错误的。
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
// JavaScript is not waiting until the for is finished !!
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
for的执行速度可能非常快,因此您无法看到结果是错误的。您可以使用执行某些请求的代码来测试它:
var start = new Date().getTime();
for (i = 0; i < 50000; ++i) {
$.ajax({
url: 'www.oneOfYourWebsites.com',
success: function(){
console.log("success");
}
});
}
var end = new Date().getTime();
var time = end - start;
alert('Execution time: ' + time);
因此,警报将非常迅速地提示,但在控制台中,您将看到ajax请求正在继续。
以下是您应该如何做到的:https://developer.mozilla.org/en-US/docs/Web/API/Performance.now