I am trying to output time taken in seconds using the built in console.time() and console.timeEnd() functions.
Currently, my code and output looks like this:
console.time('Time taken');
// do things
console.timeEnd('Time taken');
Output: Time taken: 34239.098ms
I would like to be able to pass in an optional parameter to console.timeEnd() to be able to output the results in different units of time rather than milliseconds.
Example:
console.time('Time taken');
// do things
console.timeEnd('Time taken', 's'); // or 'ms', 'm', 'h', 'd'...
Output: Time taken: 34.239s
This is the best alternative that I've currently found:
const begin = Date.now();
// do things
const end = Date.now();
const elapsedTime = (end-begin) / 1000;
console.log(`Time taken: ${elapsedTime}s`);
Output: Time taken: 34.239s
Normally I do use milliseconds with my output - and it should remain the default. However I have come across numerous asynchronous processes I'd like to easily measure final time for. Reading 12168532.35ms instead of 3.38h is slightly more difficult.
Thanks for your consideration!
I'm not an expert, but I think that globals such as console should behave as web does, if you see console timers docs, time is considered on milliseconds, and I'm not sure of your alternative, Javascript numbers are double-precision 64-bit floating point, maths operations sometimes are not very precise, I do not see this very convenient; also, milliseconds is not a complex unit to convert.
Let me know what do you think
We can't add new parameters to console methods, but the time format is implementation defined. We could make it more human readable based on the duration. I would be fine with something like 3.38h (12168532.35ms).
cc @nodejs/console
@devsnek That sounds wonderful to me! Thanks
Have you tried time-span & time-stamp npm packages..
@nvispute It looks like time-span would do what I want. However, I would much rather use what I listed under Current Alternative than introduce another dependency - especially from a largely unknown origin
Well its always a manual v/s a package :P no middle way to it.. and the alternative you listed is something i have been seeing since i start to code :) so i believe that would only be the way until something comes ups when it comes up
@nvispute What I'm suggesting as a feature is to get around the manual way and the package way - to just include it with Node.js
As it landed with v13.0.0, I think this issue can be closed.
Most helpful comment
We can't add new parameters to console methods, but the time format is implementation defined. We could make it more human readable based on the duration. I would be fine with something like
3.38h (12168532.35ms).