javascript - 测试 JavaScript 函数计算速度的最准确方法是什么?

标签 javascript performance performance-testing

我需要比较一些代码的计算速度,但我不确定最好的方法是什么。是否有某种内置计时器可以执行此操作?是否有可能获得以纳秒为单位的计算速度,或者我是否需要处理 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/

相关文章:

javascript - Angular 链接函数范围未正确更新

javascript - 在动态元素(Backbone)中调用ajax后,单击功能不起作用

python - Python 中的 Eratosthenes 筛法非常慢

recursion - 带尾递归的慢字节码

javascript - 从 postgres 数据库中获取 Node js 中的多个 Refcursor(使用 pg-promise)

来自其他输入的 Javascript 调用值

java - 在 Java 中检查二维数组中邻居的更有效方法

c++ - vector 是否比 std::array 多使用一次解引用来访问元素?

MongoDB 索引有效性评估最佳实践

java - 我可以使用 JMeter 进行非 Web 应用程序性能计量吗?