Skip to content

Instantly share code, notes, and snippets.

@AnsonH
Last active September 11, 2021 12:36
Show Gist options
  • Save AnsonH/4983920c449b062bf723f4190f544a6c to your computer and use it in GitHub Desktop.
Save AnsonH/4983920c449b062bf723f4190f544a6c to your computer and use it in GitHub Desktop.
Javascript Tip #4 - Measure function execution time
/* Tweet: https://twitter.com/AnsonH_/status/1436669886055415816?s=20 */
function slowFunction() {
for (let i = 0; i < 999999999; ++i) {
// do something...
}
}
/***** Browser example *****/
const t0 = window.performance.now();
slowFunction();
const t1 = window.performance.now();
const timeTaken = t1 - t0;
console.log(`It took ${timeTaken} ms`); // eg. "It took 836.1103000640869 ms"
/***** Node.js example *****/
const { performance } = require("perf_hooks");
const t0 = performance.now();
slowFunction();
const t1 = performance.now();
const timeTaken = t1 - t0;
console.log(`It took ${timeTaken} ms`); // eg. "It took 836.1103000640869 ms"
@AnsonH
Copy link
Author

AnsonH commented Sep 11, 2021

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