温馨提示:本站仅提供公开网络链接索引服务,不存储、不篡改任何第三方内容,所有内容版权归原作者所有
AI智能索引来源:http://www.bun.com/reference/node/perf_hooks
点击访问原文链接

Node.js perf_hooks module | API Reference | Bun

Node.js perf_hooks module | API Reference | BunBuildDocsReferenceGuidesBlogDiscord/node:perf_hooksNconstantsFcreateHistogramFeventLoopUtilizationFmonitorEventLoopDelayVperformanceCPerformanceNodeEntryFtimerify

Search the reference...

/

BuildDocsReferenceGuidesBlogDiscord/node:perf_hooksNconstantsFcreateHistogramFeventLoopUtilizationFmonitorEventLoopDelayVperformanceCPerformanceNodeEntryFtimerify

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`.

namespace constantsconst NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: numberconst NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: numberconst NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: numberconst NODE_PERFORMANCE_GC_FLAGS_FORCED: numberconst NODE_PERFORMANCE_GC_FLAGS_NO: numberconst NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: numberconst NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: numberconst NODE_PERFORMANCE_GC_INCREMENTAL: numberconst NODE_PERFORMANCE_GC_MAJOR: numberconst NODE_PERFORMANCE_GC_MINOR: numberconst NODE_PERFORMANCE_GC_WEAKCB: numberclass PerformanceNodeEntry

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

Provides detailed Node.js timing data.

The constructor of this class is not exposed to users directly.

readonly detail: any

Additional detail specific to the entryType.

readonly duration: numberreadonly entryType: 'function' | 'dns' | 'gc' | 'http2' | 'http' | 'net' | 'node'readonly name: stringreadonly startTime: numbertoJSON(): any;const performance: Performanceconst Performance: new () => Performanceconst PerformanceEntry: new () => PerformanceEntryconst PerformanceMark: new (markName: string, markOptions?: PerformanceMarkOptions) => PerformanceMarkconst PerformanceMeasure: new () => PerformanceMeasureconst PerformanceObserver: new (callback: PerformanceObserverCallback) => PerformanceObserverconst PerformanceObserverEntryList: new () => PerformanceObserverEntryListconst PerformanceResourceTiming: new () => PerformanceResourceTimingfunction createHistogram(options?: CreateHistogramOptions): RecordableHistogram;

Returns a RecordableHistogram.

{ 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." data-algolia-static="false" data-algolia-merged="false" data-type="Function">function eventLoopUtilization(utilization1?: EventLoopUtilization,utilization2?: EventLoopUtilization): EventLoopUtilization;

The eventLoopUtilization() function 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.

function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram;

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

Creates an IntervalHistogram object that samples and reports the event loop delay over time. The delays will be reported in nanoseconds.

Using a timer to detect approximate event loop delay works because the execution of timers is tied specifically to the lifecycle of the libuv event loop. That is, a delay in the loop will cause a delay in the execution of the timer, and those delays are specifically what this API is intended to detect.

import { monitorEventLoopDelay } from 'node:perf_hooks';
const h = monitorEventLoopDelay({ resolution: 20 });
h.enable();
// Do something.
h.disable();
console.log(h.min);
console.log(h.max);
console.log(h.mean);
console.log(h.stddev);
console.log(h.percentiles);
console.log(h.percentile(50));
console.log(h.percentile(99));
{ 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." data-algolia-static="false" data-algolia-merged="false" data-type="Function">function timerifyT extends (...args: any[]) => any>(fn: T,options?: TimerifyOptions): 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 { timerify, performance, PerformanceObserver } from 'node:perf_hooks';

function someFunction() {
console.log('hello world');
}

const wrapped = 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.

Type definitionsinterface ConnectionTimingInfoALPNNegotiatedProtocol: stringconnectionEndTime: numberconnectionStartTime: numberdomainLookupEndTime: numberdomainLookupStartTime: numbersecureConnectionStartTime: numberinterface CreateHistogramOptionsfigures?: 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 EventLoopMonitorOptionsresolution?: number

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

interface EventLoopUtilizationactive: numberidle: numberutilization: numberinterface FetchTimingInfodecodedBodySize: numberencodedBodySize: numberendTime: numberfinalConnectionTimingInfo: null | ConnectionTimingInfofinalNetworkRequestStartTime: numberfinalNetworkResponseStartTime: numberfinalServiceWorkerStartTime: numberpostRedirectStartTime: numberredirectEndTime: numberredirectStartTime: numberstartTime: numberinterface Histogramreadonly 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: Mapnumber, number>

Returns a Map object detailing the accumulated percentile distribution.

readonly percentilesBigInt: Mapbigint, bigint>

Returns a Map object detailing the accumulated percentile distribution.

readonly stddev: number

The standard deviation of the recorded event loop delays.

percentile(percentile: number): number;

Returns the value at the given percentile.

@param percentile

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

percentileBigInt(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 IntervalHistogramreadonly 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: Mapnumber, number>

Returns a Map object detailing the accumulated percentile distribution.

readonly percentilesBigInt: Mapbigint, bigint>

Returns a Map object detailing the accumulated percentile distribution.

readonly stddev: number

The standard deviation of the recorded event loop delays.

[Symbol.dispose](): void;

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(percentile: number): number;

Returns the value at the given percentile.

@param percentile

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

percentileBigInt(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

readonly nodeTiming: PerformanceNodeTimingonresourcetimingbufferfull: null | (ev: Event) => voidreadonly timeOrigin: numberaddEventListenerK 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

addEventListener(type: string,listener: EventListener | EventListenerObject,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

clearMarks(markName?: string): void;clearMeasures(measureName?: string): void;clearResourceTimings(resourceTimingName?: string): void;dispatchEvent(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.

eventLoopUtilization(utilization1?: EventLoopUtilization,utilization2?: EventLoopUtilization): EventLoopUtilization;

This is an alias of perf_hooks.eventLoopUtilization().

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

@param utilization1

The result of a previous call to eventLoopUtilization().

@param utilization2

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

getEntries(): PerformanceEntryList;getEntriesByName(name: string,type?: EntryType): PerformanceEntryList;getEntriesByType(type: EntryType): PerformanceEntryList;mark(markName: string,markOptions?: PerformanceMarkOptions): PerformanceMark;markResourceTiming(timingInfo: FetchTimingInfo,requestedUrl: string,initiatorType: string,global: unknown,cacheMode: string,bodyInfo: unknown,responseStatus: number,deliveryType?: string): PerformanceResourceTiming;measure(measureName: string,startMark?: string,endMark?: string): PerformanceMeasure;measure(measureName: string,options: PerformanceMeasureOptions,endMark?: string): PerformanceMeasure;now(): number;removeEventListenerK 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

removeEventListener(type: string,listener: EventListener | EventListenerObject,options?: boolean | EventListenerOptions): void;

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

MDN Reference

setResourceTimingBufferSize(maxSize: number): void;timerifyT extends (...args: any[]) => any>(fn: T,options?: TimerifyOptions): T;

This is an alias of perf_hooks.timerify().

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

toJSON(): any;interface PerformanceEntryreadonly duration: numberreadonly entryType: EntryTypereadonly name: stringreadonly startTime: numbertoJSON(): any;interface PerformanceEventMapresourcetimingbufferfull: Eventinterface PerformanceMarkreadonly detail: anyreadonly duration: numberreadonly entryType: 'mark'readonly name: stringreadonly startTime: numbertoJSON(): any;interface PerformanceMarkOptionsdetail?: anystartTime?: numberinterface PerformanceMeasurereadonly detail: anyreadonly duration: numberreadonly entryType: 'measure'readonly name: stringreadonly startTime: numbertoJSON(): any;interface PerformanceMeasureOptionsdetail?: anyduration?: numberend?: string | numberstart?: string | numberinterface 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: numberreadonly 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: stringreadonly nodeStart: number

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

readonly startTime: numberreadonly 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 PerformanceObserverdisconnect(): void;observe(options: PerformanceObserverInit): void;takeRecords(): PerformanceEntryList;interface PerformanceObserverCallbackinterface PerformanceObserverEntryListgetEntries(): PerformanceEntryList;getEntriesByName(name: string,type?: EntryType): PerformanceEntryList;getEntriesByType(type: EntryType): PerformanceEntryList;interface PerformanceObserverInitbuffered?: booleanentryTypes?: EntryType[]type?: EntryTypeinterface PerformanceResourceTimingreadonly connectEnd: numberreadonly connectStart: numberreadonly decodedBodySize: numberreadonly domainLookupEnd: numberreadonly domainLookupStart: numberreadonly duration: numberreadonly encodedBodySize: numberreadonly entryType: 'resource'readonly fetchStart: numberreadonly initiatorType: stringreadonly name: stringreadonly nextHopProtocol: stringreadonly redirectEnd: numberreadonly redirectStart: numberreadonly requestStart: numberreadonly responseEnd: numberreadonly responseStart: numberreadonly responseStatus: numberreadonly secureConnectionStart: numberreadonly startTime: numberreadonly transferSize: numberreadonly workerStart: numbertoJSON(): any;interface RecordableHistogramreadonly 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: Mapnumber, number>

Returns a Map object detailing the accumulated percentile distribution.

readonly percentilesBigInt: Mapbigint, bigint>

Returns a Map object detailing the accumulated percentile distribution.

readonly stddev: number

The standard deviation of the recorded event loop delays.

add(other: RecordableHistogram): void;

Adds the values from other to this histogram.

percentile(percentile: number): number;

Returns the value at the given percentile.

@param percentile

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

percentileBigInt(percentile: number): bigint;

Returns the value at the given percentile.

@param percentile

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

record(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 TimerifyOptionshistogram?: RecordableHistogram

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

interface UVMetricsreadonly 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'type PerformanceEntryList = PerformanceEntry[]

Resources

ReferenceDocsGuidesDiscordMerch StoreGitHubBlog 

Toolkit

RuntimePackage managerTest runnerBundlerPackage runner

Project

Bun 1.0Bun 1.1Bun 1.2Bun 1.3RoadmapContributingLicense

Baked with ❤️ in San Francisco

We're hiring →

Node.js perf_hooks module | API Reference | Bun,AI智能索引,全网链接索引,智能导航,网页索引

    The