
Security News
Insecure Agents Podcast: How to Keep AI Agents From Bypassing Security Controls
Socket CTO Ahmad Nassri discusses how to keep AI agents from bypassing package blocks, limit credential access, and monitor their actions.
Benchmark your code easily with Tinybench, a simple, tiny and light-weight 10KB (2KB minified and gzipped) benchmarking library!
You can run your benchmarks in multiple JavaScript runtimes, Tinybench is completely based on the Web APIs with proper timing using
process.hrtime or performance.now.
Event and EventTarget compatible eventsIn case you need more tiny libraries like tinypool or tinyspy, please consider submitting an RFC
$ npm install -D tinybench
You can start benchmarking by instantiating the Bench class and adding benchmark tasks to it.
import { Bench } from 'tinybench'
const bench = new Bench({ name: 'simple benchmark', time: 100 })
bench
.add('faster task', () => {
console.log('I am faster')
})
.add('slower task', async () => {
await new Promise(resolve => setTimeout(resolve, 1)) // we wait 1ms :)
console.log('I am slower')
})
await bench.run()
console.log(bench.name)
console.table(bench.table())
// Output:
// simple benchmark
// āāāāāāāāāāā¬āāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāāāāāāāāāāāā¬āāāāāāāāāā
// ā (index) ā Task name ā Latency avg (ns) ā Latency med (ns) ā Throughput avg (ops/s) ā Throughput med (ops/s) ā Samples ā
// āāāāāāāāāāā¼āāāāāāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāāāāāā¼āāāāāāāāāāāāāāāāāāāāāāāāā¼āāāāāāāāāā¤
// ā 0 ā 'faster task' ā '63768 ± 4.02%' ā '58954 ± 15255.00' ā '18562 ± 1.67%' ā '16962 ± 4849' ā 1569 ā
// ā 1 ā 'slower task' ā '1542543 ± 7.14%' ā '1652502 ± 167851.00' ā '808 ± 19.65%' ā '605 ± 67' ā 65 ā
// āāāāāāāāāāā“āāāāāāāāāāāāāāāā“āāāāāāāāāāāāāāāāāāāā“āāāāāāāāāāāāāāāāāāāāāāāā“āāāāāāāāāāāāāāāāāāāāāāāāā“āāāāāāāāāāāāāāāāāāāāāāāāā“āāāāāāāāāā
The add method accepts a task name and a task function, so it can benchmark
it! This method returns a reference to the Bench instance, so it's possible to
use it to create an another task for that instance.
Note that the task name should always be unique in an instance, because Tinybench stores the tasks based
on their names in a Map.
Also note that tinybench does not log any result by default. You can extract the relevant stats
from bench.tasks or any other API after running the benchmark, and process them however you want.
More usage examples can be found in the examples directory.
BenchTaskTaskResultEventsBoth the Task and Bench classes extend the EventTarget object. So you can attach listeners to different types of events in each class instance using the universal addEventListener and removeEventListener methods.
BenchEvents// runs on each benchmark task's cycle
bench.addEventListener('cycle', (evt) => {
const task = evt.task!;
});
// runs when timer saturation is detected for a task's measured samples
bench.addEventListener('warning', (evt) => {
const task = evt.task!;
const reason = evt.reason; // 'zero-dominated' | 'low-distinct' | 'zero-mad'
});
TaskEvents// runs only on this benchmark task's cycle
task.addEventListener('cycle', (evt) => {
const task = evt.task!;
});
BenchEventTinybench automatically detects if a task function is asynchronous by
checking if provided function is an AsyncFunction or if it returns a
Promise, by calling the provided function once.
You can also explicitly set the async option to true or false when adding
a task, thus avoiding the detection. Set async: false only for a genuinely
synchronous task; to measure the synchronous cost of a function that returns a
Promise, record it via overriddenDuration instead.
const bench = new Bench()
bench.add('asyncTask', async () => {}, { async: true })
bench.add('syncTask', () => {}, { async: false })
bench.add(
'syncTaskReturningPromiseAsAsync',
() => {
return Promise.resolve()
},
{ async: true }
)
await bench.run()
mode is set to null (default), concurrency is disabled.mode is set to 'task', each task's iterations (calls of a task function) run concurrently.mode is set to 'bench', different tasks within the bench run concurrently. Concurrent cycles.const bench = new Bench({
concurrency: 'task', // The concurrency mode to determine how tasks are run.
threshold: 10, // The maximum number of concurrent tasks to run. Defaults to Number.POSITIVE_INFINITY.
})
await bench.run()
console.table()You can convert the benchmark results to a table format suitable for
console.table() using the bench.table() method.
const table = bench.table()
console.table(table)
You can also customize the table output by providing a convert-function to the table method.
import { Bench, type ConsoleTableConverter, formatNumber, mToNs, type Task } from 'tinybench'
/**
* The default converter function for console.table output.
* Modify it as needed to customize the table format.
*/
const defaultConverter: ConsoleTableConverter = (task: Task): Record<string, number | string> => {
const state = task.result.state
return {
'Task name': task.name,
...(state === 'aborted-with-statistics' || state === 'completed'
? {
'Latency avg (ns)': `${formatNumber(mToNs(task.result.latency.mean))} \xb1 ${formatNumber(task.result.latency.rme)}%`,
'Latency med (ns)': `${formatNumber(mToNs(task.result.latency.p50))} \xb1 ${formatNumber(mToNs(task.result.latency.mad))}`,
'Throughput avg (ops/s)': `${Math.round(task.result.throughput.mean).toString()} \xb1 ${formatNumber(task.result.throughput.rme)}%`,
'Throughput med (ops/s)': `${Math.round(task.result.throughput.p50).toString()} \xb1 ${Math.round(task.result.throughput.mad).toString()}`,
Samples: task.result.latency.samplesCount,
}
: state !== 'errored'
? {
'Latency avg (ns)': 'N/A',
'Latency med (ns)': 'N/A',
'Throughput avg (ops/s)': 'N/A',
'Throughput med (ops/s)': 'N/A',
Samples: 'N/A',
Remarks: state,
}
: {
Error: task.result.error.message,
Stack: task.result.error.stack ?? 'N/A',
}),
...(state === 'aborted-with-statistics' && {
Remarks: state,
}),
}
}
const bench = new Bench({ name: 'custom table benchmark', time: 100 })
// add tasks...
console.table(bench.table(defaultConverter))
By default Tinybench does not keep the samples for latency and throughput to
minimize memory usage. Enable sample retention if you need the raw samples for
plotting, custom analysis, or exporting results.
You can enable samples retention at the bench level by setting the
retainSamples option to true when creating a Bench instance:
const bench = new Bench({ retainSamples: true })
You can also enable samples retention by setting the retainSamples option to
true when adding a task:
bench.add(
'task with samples',
() => {
// Task logic here
},
{ retainSamples: true }
)
Tinybench can utilize different timestamp providers for measuring time intervals.
By default it uses performance.now().
The timestampProvider option can be set when creating a Bench instance. It
accepts either a TimestampProvider object or shorthands for the common
providers hrtimeNow and performanceNow.
If you use bun runtime, you can also use bunNanoseconds shorthand.
You can set the timestampProvider to auto to let Tinybench choose the most
precise available timestamp provider based on the runtime.
import { Bench } from 'tinybench'
const bench = new Bench({
timestampProvider: 'hrtimeNow', // or 'performanceNow', 'bunNanoseconds', 'auto'
})
If you want to provide a custom timestamp provider, you can create an object that implements
the TimestampProvider interface:
import { Bench, TimestampProvider } from 'tinybench'
// Custom timestamp provider using Date.now()
const dateNowTimestampProvider: TimestampProvider = {
name: 'dateNow', // name of the provider
fn: Date.now, // function that returns the current timestamp
toMs: ts => ts, // convert the timestamp to milliseconds
fromMs: ts => ts, // convert milliseconds to the format used by fn()
}
const bench = new Bench({
timestampProvider: dateNowTimestampProvider,
})
You can also set the now option to a function that returns the current timestamp.
It will be converted to a TimestampProvider internally.
import { Bench } from 'tinybench'
const bench = new Bench({
now: Date.now,
})
Each timer call (performance.now(), process.hrtime.bigint(), ā¦) has a
non-zero call cost C. For a task whose true duration X is comparable
to C, the raw measured sample X + C is dominated by the timer rather
than the task.
When subtractTimerOverhead: true is set, an estimate Ä is computed
once at construction time via calibrateTimerOverhead,
and Math.max(0, raw_sample - Ä) is used as each non-overridden sample
before statistics are computed.
const bench = new Bench({ subtractTimerOverhead: true })
console.log(bench.timerOverhead) // calibrated Ä in ms (or undefined)
The calibration helper is also exported for direct use, with a
configurable estimator strategy ('median' default, or 'min' / 'p05'):
import { calibrateTimerOverhead, hrtimeNowTimestampProvider } from 'tinybench'
const overhead = calibrateTimerOverhead(hrtimeNowTimestampProvider, {
estimator: 'p05',
pairs: 1024,
warmupPairs: 64,
})
Caveats.
concurrency: 'task' ā overhead is calibrated
sequentially and does not reflect concurrent execution cost.
Construction (and run()) throws if both are set.X ā Ä) the max(0, ā¦) clamp
truncates the lower tail and biases statistics; prefer
overriddenDuration.C < R / 2,
e.g. a Date.now-class timer with >= 1 ms resolution) ā the calibration
returns 0 and the option becomes a no-op.C is not amortized. This is a deliberate trade-off:
it yields a real per-sample distribution (percentiles, MAD, saturation
detection) at the cost of a higher sub-C noise floor. For work below the
timer grain, use overriddenDuration.Ä does not cover an async task's await microtask turn ā that overhead is
inside the measured window but absent from the calibration pairs ā so async
sub-microsecond samples stay over-measured even with subtractTimerOverhead.
Use overriddenDuration for such sub-resolution work.overriddenDuration)A task function may return an object containing overriddenDuration
(in ms). That value is recorded in place of the timer-measured sample:
the timer still brackets the task function, but its measurement is
discarded and overhead correction is not applied to the substituted
value. Useful for externally-timed work or sub-overhead measurements
that the timer cannot resolve.
bench.add('externally-timed', () => {
const start = process.hrtime.bigint()
doWork()
const elapsedMs = Number(process.hrtime.bigint() - start) / 1e6
return { overriddenDuration: elapsedMs }
})
Overridden samples are excluded from Task.detectedResolution and
from timer-saturation detection.
After bench.run() (or runSync()), each task exposes
detectedResolution ā the smallest reproducibly observed positive
sample (in ms) among the timer-measured samples, or undefined when no
positive timer measurement was seen (e.g. every sample was overridden).
const task = bench.getTask('foo')
console.log(task?.detectedResolution) // e.g. 0.000041 (ā 41 ns)
When the timer's resolution dominates a task's measured distribution
(more than half zero samples, fewer than max(3, min(10, ān / 1000ā))
distinct values, or zero MAD with n > 100), tinybench dispatches a
'warning' event on both the task and the bench, carrying the matching
TimerSaturationReason:
bench.addEventListener('warning', evt => {
console.warn(`timer-saturated: ${evt.task?.name} ā ${evt.reason}`)
})
The same heuristic and estimator are exposed as standalone helpers for
custom analysis: detectTimerSaturation,
classifyTimerSaturation,
and estimateResolution.
Tinybench supports aborting benchmarks using AbortSignal at both the bench and task levels:
Abort all tasks in a benchmark by passing a signal to the Bench constructor:
const controller = new AbortController()
const bench = new Bench({ signal: controller.signal })
bench
.add('task1', () => {
// This will be aborted
})
.add('task2', () => {
// This will also be aborted
})
// Abort all tasks
controller.abort()
await bench.run()
// Both tasks will be aborted
Abort individual tasks without affecting other tasks by passing a signal to the task options:
const controller = new AbortController()
const bench = new Bench()
bench
.add(
'abortable task',
() => {
// This task can be aborted independently
},
{ signal: controller.signal }
)
.add('normal task', () => {
// This task will continue normally
})
// Abort only the first task
controller.abort()
await bench.run()
// Only 'abortable task' will be aborted, 'normal task' continues
You can abort benchmarks while they're running:
const controller = new AbortController()
const bench = new Bench({ time: 10000 }) // Long-running benchmark
bench.add(
'long task',
async () => {
await new Promise(resolve => setTimeout(resolve, 100))
},
{ signal: controller.signal }
)
// Abort after 1 second
setTimeout(() => controller.abort(), 1000)
await bench.run()
// Task will stop after ~1 second instead of running for 10 seconds
Both Bench and Task emit abort events when aborted:
const controller = new AbortController()
const bench = new Bench()
bench.add(
'task',
() => {
// Task function
},
{ signal: controller.signal }
)
const task = bench.getTask('task')
// Listen for abort events
task.addEventListener('abort', () => {
console.log('Task aborted!')
})
bench.addEventListener('abort', () => {
console.log('Bench received abort event!')
})
controller.abort()
await bench.run()
Note: When a task is aborted, task.result.aborted will be true, and the task will have completed any iterations that were running when the abort signal was received.
| Mohammad Bagher |
|---|
| Uzlopak | poyoho |
|---|
Feel free to create issues/discussions and then PRs for the project!
Your sponsorship can make a huge difference in continuing our work in open source!
The 'benchmark' package is a popular benchmarking library for JavaScript. It provides a robust API for measuring the performance of code snippets. Compared to tinybench, 'benchmark' offers more advanced features and a more comprehensive API, but it is also larger in size.
The 'perf_hooks' module is a built-in Node.js module that provides an API for measuring performance. It is more low-level compared to tinybench and requires more manual setup, but it is very powerful and flexible for detailed performance analysis.
The 'benny' package is another benchmarking tool for JavaScript. It focuses on simplicity and ease of use, similar to tinybench. However, 'benny' provides a more modern API and better integration with modern JavaScript features like async/await.
FAQs
š A simple, tiny and lightweight benchmarking library!
The npm package tinybench receives a total of 81,271,650 weekly downloads. As such, tinybench popularity was classified as popular.
We found that tinybench demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 3 open source maintainers collaborating on the project.

Security News
Socket CTO Ahmad Nassri discusses how to keep AI agents from bypassing package blocks, limit credential access, and monitor their actions.

Security News
GPT-6 Astra tried to plant malicious code in simulated open source projects using fake GitHub accounts and deceptive PRs during an assigned CTF challenge.

Security News
upm uses Node.js to deliver fast npm installs in about 250 KB, with a JavaScript API and security defaults.