Skip to content

Repository files navigation

Perf Observer License: MIT

A lightweight performance observer using native Node.js performance APIs for debugging and benchmarking.

Table of Contents

Installation

npm install @neabyte/perf-observer

Quick Start

importperffrom'@neabyte/perf-observer'// Track a function automaticallyconsttrackedFunction=perf.track(()=>{// Your code herereturn'result'})// Manual timingperf.start('my-process')// ... do work ...constduration=perf.end('my-process')// Run benchmarksconstresult=perf.benchmark(()=>{// Function to benchmark},{iterations: 1000})

API Reference

Core Methods

MethodDescriptionReturns
start(name)Start timing a processvoid
end(name)End timing and get durationnumber (ms)
track(fn, name?)Wrap function with automatic timingFunction
getStats(name?)Get performance statisticsProcessStats
findSlowProcesses(threshold?)Find processes exceeding thresholdProcessEntry[]
benchmark(fn, options?)Run benchmark testBenchmarkResult

Types

ProcessStats

PropertyTypeDescription
countnumberNumber of processes
avgDurationnumberAverage duration (ms)
minDurationnumberMinimum duration (ms)
maxDurationnumberMaximum duration (ms)
p95Durationnumber95th percentile (ms)
p99Durationnumber99th percentile (ms)

BenchmarkOptions

PropertyTypeDefaultDescription
iterationsnumber1000Number of test iterations
warmupnumbermin(100, iterations/10)Warmup iterations
maxDurationnumber60000Max test duration (ms)
outlierThresholdnumber3Outlier detection threshold
trackMemorybooleanfalseTrack memory usage
namestringfn.nameCustom benchmark name

BenchmarkResult

PropertyTypeDescription
namestringBenchmark name
iterationsnumberActual iterations completed
warmupIterationsnumberWarmup iterations performed
totalTimenumberTotal time (ms)
avgTimenumberAverage time per iteration (ms)
minTimenumberMinimum iteration time (ms)
maxTimenumberMaximum iteration time (ms)
p95Timenumber95th percentile time (ms)
p99Timenumber99th percentile time (ms)
stdDevnumberStandard deviation
outliersnumberNumber of outliers removed
memoryDeltanumber?Memory usage change (bytes)

Usage Examples

Basic Timing

// Manual timingperf.start('database-query')// Simulate database operationawaitnewPromise(resolve=>setTimeout(resolve,50))constduration=perf.end('database-query')console.log(`Query took ${duration}ms`)

Function Tracking

// Automatic timingconstexpensiveOperation=perf.track(async()=>{awaitnewPromise(resolve=>setTimeout(resolve,100))return'completed'})constresult=awaitexpensiveOperation()

Duplicate Name Behavior: Multiple functions with the same name will overwrite each other's performance data. Only the last function's data will be preserved in statistics. To avoid data loss:

  • Use unique names: perf.track(fn, 'unique-name')
  • Add hash suffixes: perf.track(fn, 'operation-' + crypto.randomBytes(4).toString('hex'))
  • Use function names: function myOperation() {} then perf.track(myOperation)

Anonymous functions all use 'anonymous' name and will overwrite each other.

Performance Statistics

// Get stats for all processesconstallStats=perf.getStats()console.log(`Average: ${allStats.avgDuration}ms`)// Get stats for specific processconstqueryStats=perf.getStats('database-query')console.log(`95th percentile: ${queryStats.p95Duration}ms`)

Benchmarking

// Simple benchmarkconstresult=perf.benchmark(()=>{returnMath.random()*1000},10000)console.log(`Average: ${result.avgTime}ms`)console.log(`Standard deviation: ${result.stdDev}ms`)// Advanced benchmark with optionsconstadvancedResult=perf.benchmark(()=>{// Simulate data processingreturnArray.from({length: 1000},(_,i)=>i*2)},{iterations: 5000,warmup: 100,trackMemory: true,outlierThreshold: 2,name: 'data-processing'})

Finding Slow Processes

// Find processes taking longer than 1 secondconstslowProcesses=perf.findSlowProcesses(1000)slowProcesses.forEach(process=>{console.log(`${process.name}: ${process.duration}ms`)})

Requirements

  • Node.js >= 22.0.0
  • TypeScript (optional, for type definitions)

Contributing

Issues and pull requests are welcome on GitHub.

License

This project is licensed under the MIT license. See the LICENSE file for more info.

Contributors

Languages