阿西河

所有教程

公众号
🌙
阿西河前端的公众号

我的收藏

    最近访问  (文章)

      教程列表

      抓包专区
      测试专区

      Node.js perf_hooks 测量异步操作的时长

      Node.js perf_hooks 测量异步操作的时长

      The following example uses the Async Hooks and Performance APIs to measure the actual duration of a Timeout operation (including the amount of time it to execute the callback).

      'use strict';
      const async_hooks = require('async_hooks');
      const {
        performance,
        PerformanceObserver
      } = require('perf_hooks');
      
      const set = new Set();
      const hook = async_hooks.createHook({
        init(id, type) {
          if (type === 'Timeout') {
            performance.mark(`Timeout-${id}-Init`);
            set.add(id);
          }
        },
        destroy(id) {
          if (set.has(id)) {
            set.delete(id);
            performance.mark(`Timeout-${id}-Destroy`);
            performance.measure(`Timeout-${id}`,
                                `Timeout-${id}-Init`,
                                `Timeout-${id}-Destroy`);
          }
        }
      });
      hook.enable();
      
      const obs = new PerformanceObserver((list, observer) => {
        console.log(list.getEntries()[0]);
        performance.clearMarks();
        observer.disconnect();
      });
      obs.observe({ entryTypes: ['measure'], buffered: true });
      
      setTimeout(() => {}, 1000);
      

      更多内容请参考:Node.js perf_hooks 性能钩子,或者通过 点击对应菜单 进行查看;


      目录
      本文目录
      目录