Els*_*ban 12 javascript frontend typescript
我ReferenceError: performance is not defined在尝试使用performance.now()来测量函数调用的执行时间时遇到错误:
export async function find(someId: string, ctx: context.IContext) {
try {
var t0 = performance.now();
var res = someModel.find(someId, ctx.cookies);
var t1 = performance.now();
console.log("Call to find took " + (t1 - t0) + " milliseconds.");
return res;
} catch (err) {
console.error(err);
throw err;
}
}
Run Code Online (Sandbox Code Playgroud)
我有什么想法可以解决这个问题?
gil*_*tic 22
我知道这是标记的前端,但如果有人遇到这个寻找node.js解决方案(像我一样),你需要首先要求perf_hooks模块的性能(在节点8.5+中可用).
const {performance} = require('perf_hooks');
const t0 = performance.now();
...
Run Code Online (Sandbox Code Playgroud)
Ben*_*uer 15
使用时您将丢失类型信息require,因此使用 TypeScript 导入“性能”的最佳方法是使用import语句:
import {performance, PerformanceObserver} from 'perf_hooks';
const observer = new PerformanceObserver(items => items.getEntries().forEach((entry) => console.log(entry)));
observer.observe({entryTypes: ['measure']});
performance.mark('start');
performance.mark('stop');
performance.measure('Measurement', 'start', 'stop');
Run Code Online (Sandbox Code Playgroud)
还要确保您@types/node在“package.json”的“依赖项”中声明。
使用 TypeScript 4 和 Node.js 14 进行测试。
小智 14
由于“perf_hook”模块导出多个构造(对象、函数、常量等),因此您需要明确指定要使用的构造。在这种情况下,您需要performance构造。声明可以通过两种方式完成:
const performance = require('perf_hooks').performance;
Run Code Online (Sandbox Code Playgroud)
或者
const { performance } = require('perf_hooks'); //object destructuring
Run Code Online (Sandbox Code Playgroud)
小智 8
是的!就像上面的答案一样,你需要添加这个..
const {
performance,
PerformanceObserver
} = require('perf_hooks');
Run Code Online (Sandbox Code Playgroud)
但您可以performance.now()在浏览器控制台或浏览器 -> 源选项卡 -> 代码片段中运行,而无需添加上述代码。
您可以阅读本文以了解更多信息。
https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now
| 归档时间: |
|
| 查看次数: |
5199 次 |
| 最近记录: |