I would like to get the amount of time the process took to fully complete. I have this code:
console.log(`Ran ${ran} equations in ${console.timeEnd()}`)
but I don't get my expected output, which is:
Ran X equations in 33.099ms // eg
instead I get
default: 33.099ms
Ran X Equations in undefined
Note that I didn't give my console.time()
a label.
How can I achieve my expected output?
CodePudding user response:
console.timeEnd
doesn't return anything; it's part of the console, as you know. Because console.timeEnd
counts in milliseconds with decimal places (unlike Date.now()
), the closest thing you'll get is with performance.now()
. We can create a custom time function:
class Time {
constructor() {
this.time = performance.now();
}
end() {
return (performance.now() - this.time).toFixed(3); // round number to lower decimal precision, like console.time()
}
}
const time = new Time();
console.time("Console measurement");
let dummyVar = 0;
for(let i = 0; i < 1000000; i ) {
// do some time consuming task
dummyVar = i;
}
console.log("Custom measurement:", time.end() "ms");
console.timeEnd("Console measurement");
I intentionally returned a number and not a string (with "ms" at the end) so you could use it better. Obviously, if you want to represent the exact output of console.timeEnd()
, simply append "ms"
to the expression in Time#end
:
class Time {
constructor() {
this.time = performance.now();
}
end() {
return (performance.now() - this.time).toFixed(3) "ms";
}
}
const time = new Time();
// dummy example
setTimeout(() => console.log(`Ran X equations in ${time.end()}`), Math.floor(Math.random() * 100));
CodePudding user response:
console.timeEnd()
returns undefined
, not what it logs. To get very close to the desired output, label the timer with the descriptive string...
const ran = 4; // you'll need to know ran before starting the timer
const label = `Ran ${ran} equations in`;
console.time(label);
// do some time consuming stuff
alert('wait a sec, then press ok')
console.timeEnd(label);