【问题标题】:How to pass a function as a parameter in a performance.now function call?如何在 performance.now 函数调用中将函数作为参数传递?
【发布时间】:2021-12-29 17:01:44
【问题描述】:

我正在尝试重构我编写的性能函数。我将此函数分离到它自己的文件中,并将它导入到一个包含我要测试的函数的文件中。

但是,当我调用性能函数并使用参数传入 twoSum 时,我得到了performance.now is not a function 的错误。

当我从性能函数 console.log fn 时,我只得到 twoSum 的输出,而不是函数本身。

import performance from './performance.js'

const twoSum = (nums, target) => {
  let res = []
  for (let i = 0; i < nums.length; i++) {
    for (let j = 1; j < nums.length; j++) {
      if ((nums[i] + nums[j] === target) & (i !== j)) {
        res.push([i, j])
      }
    }
  }
  return res[0]
}

performance(twoSum([2, 5, 5, 11], 10)) // performance.now is not a function
export default function  performance(fn) {
  let t0 = performance.now() //start time
  fn() //the function we need to measure
  let t1 = performance.now() //end time
  t1 - t0

  let avgTime = []
  const executions = 1_000_000
  for (let i = 0; i < executions; i++) {
    avgTime.push(t1 - t0)
  }
  return (avgTime.reduce((a, b) => a + b) / executions).toFixed(4)
}

【问题讨论】:

    标签: performance ecmascript-6 export performance-testing es6-modules


    【解决方案1】:

    您不能在同一范围内拥有导入的 performance 符号和 function performance() {...} 并且可以访问两者,因为它们会发生冲突,因此您必须更改两者之一的名称,以免它们发生冲突。

    将本地performance() 函数的名称更改为perf(),因为它会覆盖/隐藏包含performance.now()performance 对象,如下所示:

    export default function perf(fn) {
      let t0 = performance.now() //start time
      fn() //the function we need to measure
      let t1 = performance.now() //end time
      t1 - t0
    
      let avgTime = []
      const executions = 1_000_000
      for (let i = 0; i < executions; i++) {
        avgTime.push(t1 - t0)
      }
      return (avgTime.reduce((a, b) => a + b) / executions).toFixed(4)
    }
    

    然后,当您使用此模块时,您将使用导入符号perf


    或者,您也可以将您从系统导入的 performance 对象的名称更改为不同的本地符号名称,如下所示:

    import { performance as perf } from 'perf_hooks';
    
    
    export default function performance(fn) {
      let t0 = perf.now() //start time
      fn() //the function we need to measure
      let t1 = perf.now() //end time
      t1 - t0
    
      let avgTime = []
      const executions = 1_000_000
      for (let i = 0; i < executions; i++) {
        avgTime.push(t1 - t0)
      }
      return (avgTime.reduce((a, b) => a + b) / executions).toFixed(4)
    }
    

    【讨论】:

      猜你喜欢
      • 2011-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-03-22
      • 2019-02-22
      • 2014-06-29
      • 1970-01-01
      • 2012-12-04
      • 1970-01-01
      相关资源
      最近更新 更多