npm install --save-dev nodemark
const benchmark = require('nodemark'); const result = benchmark(myFunction, setupFunction); console.log(result); // => 14,114,886 ops/sec ±0.58% (7906233 samples) console.log(result.nanoseconds()); // => 71
Statistical SignificanceIn benchmarking, it's important to generate statistically significant results. Thankfully,
nodemarkmakes this easy:
- The margin of error is calculated for you.
- The noise caused by
nodemarkis factored out of the results.
- The garbage collector is manipulated to prevent early runs from having an unfair advantage.
- Executions done before v8 has a chance to optimize things (JIT) are ignored.
NaNin order to avoid providing misleading information.
subjectfunction. If a
setupfunction is provided, it will be invoked before every execution of
By default, the benchmark runs for about 3 seconds, but this can be overridden by passing a
durationnumber (in milliseconds). Regardless of the desired duration, the benchmark will not finish until the
subjecthas been run at least 10 times.
setupcan run asynchronously by declaring a callback argument in their signature. If you do this, you must invoke the callback to indicate that the operation is complete. When running an asyncronous benchmark, this function returns a promise. However, because
setupuse callbacks rather than promises, synchronous errors will not automatically be caught.
benchmark(callback => fs.readFile('foo.txt', callback)) .then(console.log);
There is no plan to support promises in
setupbecause it would cause too much overhead and yield inaccurate results.
class BenchmarkResultEach benchmark returns an immutable object describing the result of that benchmark. It has five properties:
mean, the average measured time in nanoseconds
error, the margin of error as a ratio of the mean
max, the fastest measured time in nanoseconds
min, the slowest measured time in nanoseconds
count, the number of times the subject was invoked and measured
.nanoseconds(precision) -> numberReturns
this.mean, rounded to the nearest whole number or the number or decimal places specified by
.microseconds(precision) -> numberSame as .nanoseconds(), but the value is in microseconds.
.milliseconds(precision) -> numberSame as .nanoseconds(), but the value is in milliseconds.
.seconds(precision) -> numberSame as .nanoseconds(), but the value is in seconds.
.hz(precision) -> numberReturns the average number of executions per second, rounded to the nearest whole number or the number of decimal places specified by
.sd(precision) -> numberReturns the standard deviation in nanoseconds, rounded to the nearest whole number or the number of decimal places specified by
.toString(format) -> numberReturns a nicely formatted string describing the result of the benchmark. By default, the
"hz"format is used, which displays ops/sec, but you can optionally specify
"seconds"to change the displayed information.