简体   繁体   English

如何在独立的javascript程序中计算运行时速度?

[英]How to calculate runtime speed in standalone javascript program?

I am doing some JavaScript exercise and thinking about ways to improve my solution(algorithm) to the exercise . 我正在做一些JavaScript练习,并思考如何改进我的解决方案(算法) 练习 I am thinking of calculating runtime speed after tweaking the code so I will know how much the speed is improved. 我正在考虑在调整代码后计算运行时速度,这样我就知道速度有多大提高了。 I searched and found this method and think I can do the same. 我搜索并找到了这种方法,并认为我也可以这样做。 Here is what I did, 这是我做的,

var d = new Date();
var startTime = d.getTime();
var endTime;

function testTargeAlgorithm(){
  ....
  ....
}

testTargetAlgorithm();

endTime = d.getTime();
console.log(endTime-startTime);

It's a very simple algorithm so I don't expect there will be notable difference between the time. 这是一个非常简单的算法,所以我不指望时间之间会有明显的差异。 But if millisecond cannot measure the speed improvement, what else can I do? 但如果毫秒无法衡量速度提升,我还能做些什么呢?

You can use performance.now() if the engine supports it. 如果引擎支持,您可以使用performance.now() This gives a time in milliseconds, with sub-millisecond precision, since the page loaded or app started. 自页面加载或应用程序启动以来,这给出了以毫秒为单位的时间,精确度为亚毫秒。

performance.now() // 26742.766999999956

I know Chrome supports it, but not sure about other browsers, node.js, or other engines standalone js engines. 我知道Chrome支持它,但不确定其他浏览器,node.js或其他引擎独立的js引擎。


Or you can run your code many times in a loop, and measure the total time taken. 或者,您可以在循环中多次运行代码,并测量所花费的总时间。

Run the same function again and again. 反复运行相同的功能。

var startTime = (new Date()).getTime();
for(var i=0;i<1000;i++) {
    testTargeAlgorithm()
}
var endTime = (new Date()).getTime();
console.log(endTime-startTime);

edited to reflect suggestions, thanks Marcel 编辑以反映建议,谢谢马塞尔

I ended up using process.hrtime() to provide nanosecond precision for measuring runtime performance. 我最终使用process.hrtime()来提供纳秒精度来测量运行时性能。 Note this method only works with Node.js. 请注意,此方法仅适用于Node.js. In Chrome & Firefox, you can use performance.now() . 在Chrome和Firefox中,您可以使用performance.now()

Even running same algorithm/function, the returned time difference still varies (in nanosecond unit tho) presumably due to CPU usage and other unknown effects, so it is suggested to run a good number of times and calculate the average. 即使运行相同的算法/功能,返回的时间差仍然会变化(以纳秒为单位),可能是由于CPU使用率和其他未知效应,因此建议运行很多次并计算平均值。 For example: 例如:

function calAvgSpeed(timesToRun, targetAlgorithm){

var diffSum = 0;
for(var i = 1; i <= timesToRun; i++){
    var startTime = process.hrtime();
    targetAlgorithm();
    var diff = process.hrtime(startTime);
    diffSum += diff[1];
   }
   return Math.floor(diffSum / times);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM