Skip to content

Instantly share code, notes, and snippets.

@funfunction
Last active January 29, 2023 10:08
Show Gist options
  • Save funfunction/91b5876a5f562e1e352aed0fcabc3858 to your computer and use it in GitHub Desktop.
Save funfunction/91b5876a5f562e1e352aed0fcabc3858 to your computer and use it in GitHub Desktop.
/**
@func
log how long it takes to run a block of code
- for a supplied number of times
@warning
the supplied func runs in a loop
- so first make sure there are no log statements in the func
- either comment them out, or replace them with lMock...
- const l = s => undefined; //lMock
@usage
timeInLoop("createLruMap3", 1e6,
() => {
const { write, read } = createLruMap(3);
write("a", "Apple");
read("a");
});
@param {string} desc - usually the func name, or something that describes the block of code being run in the loop
@param {number} loopCount - how many times to run the code block
@param {Function} fn - either a block of code wrapped in a lambda, or any regular func
*/
export const timeInLoop = (desc, loopCount, fn) => {
const d = `${desc}: ${loopCount.toExponential()}`; //concat desc and loopCount
console.time(d);
for (let i = 0; i < loopCount; i++) {
fn();
}
console.timeEnd(d);
};
/**
@func async variant
@param {string} desc
@param {number} loopCount
@param {Function} fn - must be an async func that returns a promise
*/
export const timeInLoopAsync = async (desc, loopCount, fn) => {
const d = `${desc}: ${loopCount.toExponential()}`; //concat desc and loopCount
console.time(d);
for (let i = 0; i < loopCount; i++) {
await fn();
}
console.timeEnd(d);
};
//@tests
//test a.
const sleeper = ms => new Promise(resolve => setTimeout(resolve, ms));
timeInLoopAsync("sleeper01", 1, () => sleeper(5000));
/*
output:
sleeper: 1e+0: 5.008s
*/
//test b.
const fn = async () => {
console.log("hello");
await sleeper(5000);
console.log("goodbye");
};
timeInLoopAsync("sleeperWrapped", 1, () => fn());
/*
output:
hello
goodbye
sleeperWrapped: 1e+0: 5.008s
*/
@richytong
Copy link

thank you for this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment