typescript 参考错误:使用www.example.com()时未定义性能performance.now()

8oomwypt  于 2023-03-04  发布在  TypeScript
关注(0)|答案(5)|浏览(288)

我在尝试使用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;
      }
    }

你知道我该怎么补救吗?

oprakyz7

oprakyz71#

我知道这是标记的前端,但如果有人遇到这个寻找node.js解决方案(像我一样),您需要首先从perf_hooks模块(在节点8.5+中可用)获得性能。

const {performance} = require('perf_hooks');
const t0 = performance.now();
...
ymdaylpp

ymdaylpp2#

由于'perf_hook'模块导出多个构造(对象、函数、常量等),您需要显式指定要使用的构造。在这种情况下,您需要performance构造。声明可以通过两种方式完成:

const performance = require('perf_hooks').performance;

const { performance } = require('perf_hooks'); //object destructuring
snvhrwxg

snvhrwxg3#

使用require时,您将丢失类型信息,因此使用TypeScript导入“performance”的最佳方法是使用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');

还要确保在“package.json”的“依赖项”中声明了@types/node
使用TypeScript 4和Node.js 14进行测试。

x7yiwoj4

x7yiwoj44#

是的!和上面的答案一样,你需要加上这个。

const {
      performance,
      PerformanceObserver
    } = require('perf_hooks');

但是你可以在你的浏览器控制台中或者在你的浏览器-〉源标签-〉snippet中运行performance.now(),而不需要添加上面的代码。
你可以读这篇文章来了解更多关于这方面的知识。
https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now

myzjeezk

myzjeezk5#

try {
        var t0 =  Date.now()

        var res = someModel.find(someId, ctx.cookies);

        var t1 = Date.now()
        console.log("Call to find took " + (t1 - t0) + " milliseconds.");

        return res;
      } catch (err) {
        console.error(err);
        throw err;
      }
    }

相关问题