【发布时间】: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