title: How to use perf_hooks to measure async operations?
body: <p>Here is a code that describes two async operations performed by the <code>foo</code> method:</p>
  
  <pre><code>const foo = async () =&gt; {
    await new Promise((resolve) =&gt; {
      setTimeout(() =&gt; {
        resolve();
      }, Math.random() * 100);
    });
  
    await new Promise((resolve) =&gt; {
      setTimeout(() =&gt; {
        resolve();
      }, 100);
    });
  };
  
  Promise.all([
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo()
  ])
  </code></pre>
  
  <p>I want to measure how long does each async operation takes and then how long does each <code>foo</code> execution takes in total.</p>
  
  <p>My first attempt was:</p>
  
  <pre><code>const { PerformanceObserver, performance } = require('perf_hooks');
  
  const obs = new PerformanceObserver((items) =&gt; {
    console.log('performance-observer', items.getEntries());
  });
  
  obs.observe({
    entryTypes: ['measure']
  });
  
  const foo = async () =&gt; {
    performance.mark('A');
  
    await new Promise((resolve) =&gt; {
      setTimeout(() =&gt; {
        resolve();
      }, Math.random() * 100);
    });
  
    performance.mark('B');
  
    await new Promise((resolve) =&gt; {
      setTimeout(() =&gt; {
        resolve();
      }, 100);
    });
  
    performance.mark('C');
  
    performance.measure('A to B', 'A', 'B');
    performance.measure('A to C', 'A', 'C');
    performance.measure('B to C', 'B', 'C');
  
    performance.clearMarks();
  };
  
  Promise.all([
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo(),
    foo()
  ]);
  </code></pre>
  
  <p>However, this (as expected) throws an error:</p>
  
  <pre><code>(node:29277) UnhandledPromiseRejectionWarning: Error [ERR_INVALID_PERFORMANCE_MARK]: The "B" performance mark has not been set
      at Performance.measure (perf_hooks.js:396:13)
      at foo (/Users/gajus/Documents/dev/temp/test.js:30:15)
      at async Promise.all (index 0)
  </code></pre>
  
  <p>This happens because there is no relation between an instance of <code>PerformanceObserver</code> and individual performance marks.</p>
  
  <p>How to use <a href="https://nodejs.org/api/perf_hooks.html" rel="nofollow noreferrer"><code>perf_hooks</code></a> to measure async operations?</p>