如何在performance.now函数调用中传递函数作为参数



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

然而,当我调用性能函数并传递带有参数的twoSum时,我得到了performance.now is not a function的错误。

当我从性能函数console.logfn时,我只得到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符号和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)
}

最新更新