我需要比较一些代码的计算速度,但我不确定最好的方法是什么。是否有某种内置计时器可以执行此操作?是否有可能获得以纳秒为单位的计算速度,或者我是否需要处理 JavaScript 通常使用的毫秒级?
最佳答案
我遇到了 performance API .您正在寻找的可能是 Performance.now()
,它将为您提供微秒级精度。
The
Performance.now()
method returns a DOMHighResTimeStamp, measured in milliseconds, accurate to one thousandth of a millisecond equal to the number of milliseconds since the PerformanceTiming.navigationStart property and the call to the method (source).
MDN提供的例子是:
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")
可用于多次测试特定短代码的性能的函数,您可以使用以下函数:
/**
* Finds the performance for a given function
* function fn the function to be executed
* int n the amount of times to repeat
* return array [time elapsed for n iterations, average execution frequency (executions per second)]
*/
function getPerf(fn, n) {
var t0, t1;
t0 = performance.now();
for (var i = 0; i < n; i++) {
fn(i)
}
t1 = performance.now();
return [t1 - t0, repeat * 1000 / (t1 - t0)];
}
返回单次执行 fn(i)
的时间量(以毫秒为单位)和执行频率(每秒执行次数)。 n
值越高,精度越高,但测试时间越长。参数 i
可以包含在要测试的函数中,它包含函数的当前迭代。
关于javascript - 测试 JavaScript 函数计算速度的最准确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20821973/