Bun

Node.js module

perf_hooks

The 'node:perf_hooks' module provides performance measurement APIs based on the User Timing specification. It includes performance.now(), performance.mark, performance.measure, and PerformanceObserver.

Use it to benchmark code execution, measure memory usage, and observe performance entries for timely optimization.

Works in Bun

Missing event loop delay monitoring. It's recommended to use the `performance` global instead of `perf_hooks.performance`.

Type definitions

  • interface CreateHistogramOptions

    • figures?: number

      The number of accuracy digits. Must be a number between 1 and 5.

    • highest?: number | bigint

      The maximum recordable value. Must be an integer value greater than min.

    • lowest?: number | bigint

      The minimum recordable value. Must be an integer value greater than 0.

  • interface EventLoopMonitorOptions

    • resolution?: number

      The sampling rate in milliseconds. Must be greater than zero.

  • interface EventLoopUtilization

  • interface Histogram

    • readonly count: number

      The number of samples recorded by the histogram.

    • readonly countBigInt: bigint

      The number of samples recorded by the histogram. v17.4.0, v16.14.0

    • readonly exceeds: number

      The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.

    • readonly exceedsBigInt: bigint

      The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.

    • readonly max: number

      The maximum recorded event loop delay.

    • readonly maxBigInt: number

      The maximum recorded event loop delay. v17.4.0, v16.14.0

    • readonly mean: number

      The mean of the recorded event loop delays.

    • readonly min: number

      The minimum recorded event loop delay.

    • readonly minBigInt: bigint

      The minimum recorded event loop delay. v17.4.0, v16.14.0

    • readonly percentiles: Map<number, number>

      Returns a Map object detailing the accumulated percentile distribution.

    • readonly percentilesBigInt: Map<bigint, bigint>

      Returns a Map object detailing the accumulated percentile distribution.

    • readonly stddev: number

      The standard deviation of the recorded event loop delays.

    • percentile: number
      ): number;

      Returns the value at the given percentile.

      @param percentile

      A percentile value in the range (0, 100].

    • percentile: number
      ): bigint;

      Returns the value at the given percentile.

      @param percentile

      A percentile value in the range (0, 100].

    • reset(): void;

      Resets the collected histogram data.

  • interface IntervalHistogram

    • readonly count: number

      The number of samples recorded by the histogram.

    • readonly countBigInt: bigint

      The number of samples recorded by the histogram. v17.4.0, v16.14.0

    • readonly exceeds: number

      The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.

    • readonly exceedsBigInt: bigint

      The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.

    • readonly max: number

      The maximum recorded event loop delay.

    • readonly maxBigInt: number

      The maximum recorded event loop delay. v17.4.0, v16.14.0

    • readonly mean: number

      The mean of the recorded event loop delays.

    • readonly min: number

      The minimum recorded event loop delay.

    • readonly minBigInt: bigint

      The minimum recorded event loop delay. v17.4.0, v16.14.0

    • readonly percentiles: Map<number, number>

      Returns a Map object detailing the accumulated percentile distribution.

    • readonly percentilesBigInt: Map<bigint, bigint>

      Returns a Map object detailing the accumulated percentile distribution.

    • readonly stddev: number

      The standard deviation of the recorded event loop delays.

    • Disables the update interval timer when the histogram is disposed.

      const { monitorEventLoopDelay } = require('node:perf_hooks');
      {
        using hist = monitorEventLoopDelay({ resolution: 20 });
        hist.enable();
        // The histogram will be disabled when the block is exited.
      }
      
    • disable(): boolean;

      Disables the update interval timer. Returns true if the timer was stopped, false if it was already stopped.

    • enable(): boolean;

      Enables the update interval timer. Returns true if the timer was started, false if it was already started.

    • percentile: number
      ): number;

      Returns the value at the given percentile.

      @param percentile

      A percentile value in the range (0, 100].

    • percentile: number
      ): bigint;

      Returns the value at the given percentile.

      @param percentile

      A percentile value in the range (0, 100].

    • reset(): void;

      Resets the collected histogram data.

  • interface Performance

    EventTarget is a DOM interface implemented by objects that can receive events and may have listeners for them.

    MDN Reference

    • onresourcetimingbufferfull: null | (ev: Event) => void
    • readonly timeOrigin: number
    • addEventListener<K extends 'resourcetimingbufferfull'>(
      type: K,
      listener: (ev: PerformanceEventMap[K]) => void,
      options?: boolean | AddEventListenerOptions
      ): void;

      Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

      The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

      When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

      When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

      When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

      If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

      The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

      MDN Reference

      type: string,
      options?: boolean | AddEventListenerOptions
      ): void;

      Appends an event listener for events whose type attribute value is type. The callback argument sets the callback that will be invoked when the event is dispatched.

      The options argument sets listener-specific options. For compatibility this can be a boolean, in which case the method behaves exactly as if the value was specified as options's capture.

      When set to true, options's capture prevents callback from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. When false (or not present), callback will not be invoked when event's eventPhase attribute value is CAPTURING_PHASE. Either way, callback will be invoked if event's eventPhase attribute value is AT_TARGET.

      When set to true, options's passive indicates that the callback will not cancel the event by invoking preventDefault(). This is used to enable performance optimizations described in § 2.8 Observing event listeners.

      When set to true, options's once indicates that the callback will only be invoked once after which the event listener will be removed.

      If an AbortSignal is passed for options's signal, then the event listener will be removed when signal is aborted.

      The event listener is appended to target's event listener list and is not appended if it has the same type, callback, and capture.

      MDN Reference

    • markName?: string
      ): void;
    • measureName?: string
      ): void;
    • resourceTimingName?: string
      ): void;
    • event: Event
      ): boolean;

      Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise.

    • utilization1?: EventLoopUtilization,
      utilization2?: EventLoopUtilization

      The eventLoopUtilization() method returns an object that contains the cumulative duration of time the event loop has been both idle and active as a high resolution milliseconds timer. The utilization value is the calculated Event Loop Utilization (ELU).

      If bootstrapping has not yet finished on the main thread the properties have the value of 0. The ELU is immediately available on Worker threads since bootstrap happens within the event loop.

      Both utilization1 and utilization2 are optional parameters.

      If utilization1 is passed, then the delta between the current call's active and idle times, as well as the corresponding utilization value are calculated and returned (similar to process.hrtime()).

      If utilization1 and utilization2 are both passed, then the delta is calculated between the two arguments. This is a convenience option because, unlike process.hrtime(), calculating the ELU is more complex than a single subtraction.

      ELU is similar to CPU utilization, except that it only measures event loop statistics and not CPU usage. It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). No other CPU idle time is taken into consideration. The following is an example of how a mostly idle process will have a high ELU.

      import { eventLoopUtilization } from 'node:perf_hooks';
      import { spawnSync } from 'node:child_process';
      
      setImmediate(() => {
        const elu = eventLoopUtilization();
        spawnSync('sleep', ['5']);
        console.log(eventLoopUtilization(elu).utilization);
      });
      

      Although the CPU is mostly idle while running this script, the value of utilization is 1. This is because the call to child_process.spawnSync() blocks the event loop from proceeding.

      Passing in a user-defined object instead of the result of a previous call to eventLoopUtilization() will lead to undefined behavior. The return values are not guaranteed to reflect any correct state of the event loop.

      @param utilization1

      The result of a previous call to eventLoopUtilization().

      @param utilization2

      The result of a previous call to eventLoopUtilization() prior to utilization1.

    • markName: string,
    • timingInfo: FetchTimingInfo,
      requestedUrl: string,
      initiatorType: string,
      global: unknown,
      cacheMode: string,
      bodyInfo: unknown,
      responseStatus: number,
      deliveryType?: string
    • measureName: string,
      startMark?: string,
      endMark?: string
      measureName: string,
      endMark?: string
    • now(): number;
    • removeEventListener<K extends 'resourcetimingbufferfull'>(
      type: K,
      listener: (ev: PerformanceEventMap[K]) => void,
      options?: boolean | EventListenerOptions
      ): void;

      Removes the event listener in target's event listener list with the same type, callback, and options.

      MDN Reference

      type: string,
      options?: boolean | EventListenerOptions
      ): void;

      Removes the event listener in target's event listener list with the same type, callback, and options.

      MDN Reference

    • maxSize: number
      ): void;
    • timerify<T extends (...args: any[]) => any>(
      fn: T,
      ): T;

      This property is an extension by Node.js. It is not available in Web browsers.

      Wraps a function within a new function that measures the running time of the wrapped function. A PerformanceObserver must be subscribed to the 'function' event type in order for the timing details to be accessed.

      import { performance, PerformanceObserver } from 'node:perf_hooks';
      
      function someFunction() {
        console.log('hello world');
      }
      
      const wrapped = performance.timerify(someFunction);
      
      const obs = new PerformanceObserver((list) => {
        console.log(list.getEntries()[0].duration);
      
        performance.clearMarks();
        performance.clearMeasures();
        obs.disconnect();
      });
      obs.observe({ entryTypes: ['function'] });
      
      // A performance timeline entry will be created
      wrapped();
      

      If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported once the finally handler is invoked.

    • toJSON(): any;
  • interface PerformanceEntry

  • interface PerformanceMark

  • interface PerformanceMarkOptions

  • interface PerformanceMeasure

  • interface PerformanceMeasureOptions

  • interface PerformanceNodeTiming

    This property is an extension by Node.js. It is not available in Web browsers.

    Provides timing details for Node.js itself. The constructor of this class is not exposed to users.

    • readonly bootstrapComplete: number

      The high resolution millisecond timestamp at which the Node.js process completed bootstrapping. If bootstrapping has not yet finished, the property has the value of -1.

    • readonly duration: number
    • readonly entryType: 'node'
    • readonly environment: number

      The high resolution millisecond timestamp at which the Node.js environment was initialized.

    • readonly idleTime: number

      The high resolution millisecond timestamp of the amount of time the event loop has been idle within the event loop's event provider (e.g. epoll_wait). This does not take CPU usage into consideration. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of 0.

    • readonly loopExit: number

      The high resolution millisecond timestamp at which the Node.js event loop exited. If the event loop has not yet exited, the property has the value of -1. It can only have a value of not -1 in a handler of the 'exit' event.

    • readonly loopStart: number

      The high resolution millisecond timestamp at which the Node.js event loop started. If the event loop has not yet started (e.g., in the first tick of the main script), the property has the value of -1.

    • readonly name: string
    • readonly nodeStart: number

      The high resolution millisecond timestamp at which the Node.js process was initialized.

    • readonly startTime: number
    • readonly uvMetricsInfo: UVMetrics

      This is a wrapper to the uv_metrics_info function. It returns the current set of event loop metrics.

      It is recommended to use this property inside a function whose execution was scheduled using setImmediate to avoid collecting metrics before finishing all operations scheduled during the current loop iteration.

    • readonly v8Start: number

      The high resolution millisecond timestamp at which the V8 platform was initialized.

    • toJSON(): any;
  • interface PerformanceResourceTiming

  • interface PerformanceTimerifyOptions

    • histogram?: RecordableHistogram

      A histogram object created using perf_hooks.createHistogram() that will record runtime durations in nanoseconds.

  • interface RecordableHistogram

    • readonly count: number

      The number of samples recorded by the histogram.

    • readonly countBigInt: bigint

      The number of samples recorded by the histogram. v17.4.0, v16.14.0

    • readonly exceeds: number

      The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.

    • readonly exceedsBigInt: bigint

      The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold.

    • readonly max: number

      The maximum recorded event loop delay.

    • readonly maxBigInt: number

      The maximum recorded event loop delay. v17.4.0, v16.14.0

    • readonly mean: number

      The mean of the recorded event loop delays.

    • readonly min: number

      The minimum recorded event loop delay.

    • readonly minBigInt: bigint

      The minimum recorded event loop delay. v17.4.0, v16.14.0

    • readonly percentiles: Map<number, number>

      Returns a Map object detailing the accumulated percentile distribution.

    • readonly percentilesBigInt: Map<bigint, bigint>

      Returns a Map object detailing the accumulated percentile distribution.

    • readonly stddev: number

      The standard deviation of the recorded event loop delays.

    • ): void;

      Adds the values from other to this histogram.

    • percentile: number
      ): number;

      Returns the value at the given percentile.

      @param percentile

      A percentile value in the range (0, 100].

    • percentile: number
      ): bigint;

      Returns the value at the given percentile.

      @param percentile

      A percentile value in the range (0, 100].

    • val: number | bigint
      ): void;
      @param val

      The amount to record in the histogram.

    • recordDelta(): void;

      Calculates the amount of time (in nanoseconds) that has passed since the previous call to recordDelta() and records that amount in the histogram.

    • reset(): void;

      Resets the collected histogram data.

  • interface UVMetrics

    • readonly events: number

      Number of events that have been processed by the event handler.

    • readonly eventsWaiting: number

      Number of events that were waiting to be processed when the event provider was called.

    • readonly loopCount: number

      Number of event loop iterations.

  • type EntryType = 'dns' | 'function' | 'gc' | 'http2' | 'http' | 'mark' | 'measure' | 'net' | 'node' | 'resource'