在JavaScript中测试函数计算速度的最准确方法是什么? [英] What is the most accurate way to test the computation speed of a function in JavaScript?

查看:72
本文介绍了在JavaScript中测试函数计算速度的最准确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要比较一些代码的计算速度,但我不确定最好的方法是什么。是否有某种内置计时器可以做到这一点?是否有可能以纳秒为单位获得计算速度,或者我是否需要处理JavaScript通常使用的毫秒数?

I need to compare the computation speed of some code, but I'm not sure what the best way to do that is. Is there some kind of built-in timer to do this? And is it possible to get the computation speed in nanoseconds, or do I need to deal with the milliseconds JavaScript usually works with?

推荐答案

我遇到了性能API 。您正在寻找的可能是 Performance.now(),它将为您提供微秒级的优势。

I came across the performance API. What you're looking for is probably Performance.now(), which will give you microsecond percision.


Performance.now() 方法返回 DOMHighResTimeStamp ,以毫秒为单位测量
,精确到千分之一毫秒等于
自之后的毫秒数 PerformanceTiming.navigationStart
属性和请致电(来源)。

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提供的示例是:

The example MDN provides is:

var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.")

您可以用来多次测试特定短代码的性能的函数,您可以使用以下代码:

A function you could use to test the performance of a specific short piece of code multiple times, you could use the following:

/**
 * 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 可以包含在要测试的函数中,该函数包含函数的当前迭代。

Which returns the amount of time a single execution of fn(i) takes in milliseconds, and the frequency of execution (executions per second). The higher the n value, the more precision this has, but the longer it takes to test. The argument i can be included in the function to be tested, which contains the current iteration of the function.

这篇关于在JavaScript中测试函数计算速度的最准确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆