Last active
January 29, 2023 10:08
-
-
Save funfunction/91b5876a5f562e1e352aed0fcabc3858 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
@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); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
@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 | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thank you for this.