Skip to content

Instantly share code, notes, and snippets.

@ghiden
Last active October 30, 2023 19:49
Show Gist options
  • Save ghiden/5631aebf700d6c9e7256d44cc21b4c7d to your computer and use it in GitHub Desktop.
Save ghiden/5631aebf700d6c9e7256d44cc21b4c7d to your computer and use it in GitHub Desktop.
estimate job completion time in JS
// To run: node job-completion-estimate
function sleep() {
return new Promise((resolve) => {
// add a random jitter of +-0.5 seconds
setTimeout(() => resolve(), 1000 - (Math.random() - 0.5) * 1000);
});
}
function humanReadableTime(duration) {
const milliseconds = parseInt((duration % 1000) / 100, 10);
const seconds = Math.floor((duration / 1000) % 60);
const minutes = Math.floor((duration / (1000 * 60)) % 60);
const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
return `${hours} hour(s) ${minutes} minute(s) ${seconds}.${milliseconds} second(s)`;
}
const numberOfJobs = 100;
async function main() {
const initTime = new Date();
let totalTimeSpent = 0;
for (let i = 1; i <= numberOfJobs; i += 1) {
const start = new Date();
await sleep();
const end = new Date();
const elapsedTime = end - start; // in milliseconds
// CR + clear line
process.stdout.write('\r\x1b[2K');
process.stdout.write(`Elapsed time: ${elapsedTime}ms\t|| `);
totalTimeSpent += elapsedTime;
const remainingJobs = numberOfJobs - i;
const avgTimeSpent = totalTimeSpent / i;
const estimate = humanReadableTime(avgTimeSpent * remainingJobs);
process.stdout.write(`Remaining job count: ${remainingJobs} => time remaining estimate: ${estimate}`);
}
return initTime;
}
main()
.then((startTime) => {
const end = new Date();
const elapsedTime = end - startTime; // in milliseconds
console.log(`\nElapsed time: ${elapsedTime}ms`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment