timeandreturn
A simple utility library to get the elapsed time of a block of code. Designed to easily drop into existing code with minimal changes, for easy performance profiling.
Installation
via npm
npm install timeandreturn
Usage
Say you have a section of code
// ...let a = ;let b = ;return ;
You want to know how long these three lines of code take to run. You can wrap this block of code with timeAndReturn
.
const timeAndReturn = timeAndReturn; // ...return ;
The return value of foobar
is returned by timeAndReturn
, so the logic of the program is unchanged, but elapsedTime
is captured.
If you only want to log elapsedTime
, a logTimeAndReturn
variant is provided.
const logTimeAndReturn = logTimeAndReturn; // ...// Prints: "() => { let a = foo(); let b = bar(); return f ..." ran for 0.00014059999999881256 secondsreturn ;
Async
If block
returns a Promise
, callback
is called when that Promise
resolves.
const logTimeAndReturn = logTimeAndReturn; // ...// Prints: "async () => { let a = foo(); let b = bar(); aw ..." ran for 1.000469800000079 secondsreturn ;
API
/** * Call callback with the time taken to run block, and return the result of block * * If block returns a Promise, call callback after promise resolves. * * Elapsed time is given in milliseconds. */timeAndReturncallback:void, block:T: T
/** * Log the time taken to run block, and return the result of block */logTimeAndReturnblock:T: T