Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round console.time logs?

When I use console.time and console.timeEnd to measure the execution speed of a function or code snippet in JavaScript it prints this to the console:

timer: 14657.580078125 ms

How do I round this to the nearest integer or some other digit? I've looked at the documentation for both of these functions and neither gives me a clue how to do this.

like image 492
leo848 Avatar asked Mar 20 '26 13:03

leo848


2 Answers

You'd have a better shot with the Performance API, since console timers are not exposed programmatically.

There are a couple of things you could do with the API. You could use a high resolution timestamp:

let ts = performance.now();
//some code later
let measure = performance.now() - ts;

That would get you the time in milliseconds with the decimals format you have with console timers. If you need it on seconds then you can just as well do:

console.log(Math.round(measure/1000));

The Performance api has several other way to mark timestamps and measure the difference. Take a look at it.

An example taken from MDN:

const markerNameA = "example-marker-a"
const markerNameB = "example-marker-b"

// Run some nested timeouts, and create a PerformanceMark for each.
performance.mark(markerNameA);
setTimeout(function() {
  performance.mark(markerNameB);
  setTimeout(function() {

    // Create a variety of measurements.
    performance.measure("measure a to b", markerNameA, markerNameB);
    performance.measure("measure a to now", markerNameA);
    performance.measure("measure from navigation start to b", undefined, markerNameB);
    performance.measure("measure from navigation start to now");

    // Pull out all of the measurements.
    console.log(performance.getEntriesByType("measure"));

    // Finally, clean up the entries.
    performance.clearMarks();
    performance.clearMeasures();
  }, 1000);
}, 1000);
like image 73
MinusFour Avatar answered Mar 22 '26 01:03

MinusFour


Unfortunately, you will not get console.time and console.timeEnd (methods of the console object) to do anything other than the output you've already seen exclusively in the console.

Perhaps it is too bad that console.timeEnd returns undefined instead of returning the same duration that it puts into the console. But, even if it did return that duration, and you set a variable (and rounded it), your console would still show those un-rounded values in the log. There's no way to change this behavior without hacking each javascript engine your code runs on and that's not practical.

For rounded values, you'll have to forget about console.time and console.timeEnd. Those won't assist.

like image 42
Lonnie Best Avatar answered Mar 22 '26 02:03

Lonnie Best



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!