【问题标题】:ReferenceError: performance is not defined when using performance.now()ReferenceError:使用 performance.now() 时未定义性能
【发布时间】:2018-03-08 07:06:57
【问题描述】:

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

有什么办法可以解决这个问题吗?

【问题讨论】:

  • 性能在哪里定义?这是在客户端还是服务器上完成?
  • 你在使用类似firefox的浏览器吗?
  • 我没有在任何地方定义它,因为我认为这是标准库的一部分。任何帮助如何做到这一点? @Vatsal 我在谷歌浏览器上。
  • 奇怪..我刚刚做了一个示例程序。它对我有用jsbin.com/vowinaloni/edit?js,console,output

标签: javascript typescript frontend


【解决方案1】:

使用 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');

还要确保您在“package.json”的“依赖项”中声明了@types/node

使用 TypeScript 4 和 Node.js 14 测试。

【讨论】:

    【解决方案2】:

    是的!像上面的答案你需要添加这个..

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

    但您可以在浏览器控制台或浏览器 -> 源选项卡 -> sn-p 中运行 performance.now(),而无需添加上述代码。

    您可以阅读本文以了解更多信息。

    https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_now

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 谢谢,performance 在 Node 16 中似乎是全局的,但需要在旧版本上导入模块。
        猜你喜欢
        • 2012-08-24
        • 1970-01-01
        • 2017-10-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-02-04
        • 1970-01-01
        • 2015-10-04
        相关资源
        最近更新 更多