Skip to content

Instantly share code, notes, and snippets.

@sejas
Created September 16, 2022 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sejas/0df146eff480b94ed9c4da4544cfa26c to your computer and use it in GitHub Desktop.
Save sejas/0df146eff480b94ed9c4da4544cfa26c to your computer and use it in GitHub Desktop.
Performance
// Modify the destination object and copy paste this script in the chrome dev tools.
// Very useful to track performance for API requests.
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function performanceURL(url, sampleSize, sleepMs = 1000) {
const performanceList = [];
for (let i = 0; i < sampleSize; i++) {
const t0 = performance.now();
await fetch(url);
const t1 = performance.now();
performanceList.push(t1 - t0);
console.log(`Request ${i}: ${t1 - t0}ms`);
await sleep(sleepMs);
}
return performanceList;
}
function mean(arr) {
return arr.reduce((a, b) => a + b) / arr.length;
}
async function calculatePerformance(destinations, sampleSize = 10) {
const results = {};
for (let [key, url] of Object.entries(destinations)) {
console.log(`Calculating performance for ${key}`);
const performanceList = await performanceURL(url, sampleSize);
results[key] = {
performanceList,
mean: mean(performanceList),
};
console.log(`## Mean for ${key}: ${results[key].mean}ms`);
}
window.results = results;
console.log(results);
return results;
}
calculatePerformance(
// MODIFY THE DESTINATION OBJECT
{
siteOne: "/1",
sitesTwo: "/2",
},
3
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment