我在尝试使用performance.now()测量函数调用的执行时间时收到错误ReferenceError: performance is not defined
:
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;
}
}
你知道我该怎么补救吗?
5条答案
按热度按时间oprakyz71#
我知道这是标记的前端,但如果有人遇到这个寻找node.js解决方案(像我一样),您需要首先从perf_hooks模块(在节点8.5+中可用)获得性能。
ymdaylpp2#
由于'perf_hook'模块导出多个构造(对象、函数、常量等),您需要显式指定要使用的构造。在这种情况下,您需要
performance
构造。声明可以通过两种方式完成:或
snvhrwxg3#
使用
require
时,您将丢失类型信息,因此使用TypeScript导入“performance”的最佳方法是使用import
语句:还要确保在“package.json”的“依赖项”中声明了
@types/node
。使用TypeScript 4和Node.js 14进行测试。
x7yiwoj44#
是的!和上面的答案一样,你需要加上这个。
但是你可以在你的浏览器控制台中或者在你的浏览器-〉源标签-〉snippet中运行
performance.now()
,而不需要添加上面的代码。你可以读这篇文章来了解更多关于这方面的知识。
https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now
myzjeezk5#