Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is console.time() safe in node.js?

I have a little snippet of node.js code in front of me that looks like this:

console.time("queryTime");
doAsyncIOBoundThing(function(err, results) {
    console.timeEnd("queryTime");
    // Process the results...
});

And of course when I run this on my (otherwise idle) development system, I get a nice console message like this:

queryTime: 564ms

However, if I put this into production, won't there likely be several async calls in progress simultaneously, and each of them will overwrite the previous timer? Or does node have some sort of magical execution context that gives each "thread of execution" a separate console timer namespace?

like image 365
stickfigure Avatar asked Mar 11 '13 20:03

stickfigure


People also ask

Does console log slow down NodeJS?

As said above, the console. log is asynchronous and non-blocking, so it would not slow your application too much except one tick for the function invocation. But it is a good habit to use some module to turn some logs of certain level off when deploy it in production instead of using console.

What is the purpose of console time method?

The console. time() method starts a timer you can use to track how long an operation takes. You give each timer a unique name, and may have up to 10,000 timers running on a given page. When you call console.

Can we use console log in node JS?

js provides a console module which provides tons of very useful ways to interact with the command line. It is basically the same as the console object you find in the browser. The most basic and most used method is console. log() , which prints the string you pass to it to the console.

What is the use of console log () method in node JS?

log() function from console class of Node. js is used to display the messages on the console. It prints to stdout with newline. Parameter: This function contains multiple parameters which are to be printed.


3 Answers

Just use unique labels and it will be safe. That's why you use a label, to uniquely identify the start time.

As long as you don't accidentally use a label twice everything will work exactly as intended. Also note that node has usually only one thread of execution.

like image 92
Zeta Avatar answered Sep 20 '22 16:09

Zeta


Wouldn't this simple code work?

var labelWithTime = "label " + Date.now();
console.time(labelWithTime);
// Do something
console.timeEnd(labelWithTime);
like image 24
Tal Tikotzki Avatar answered Sep 21 '22 16:09

Tal Tikotzki


Consider new NodeJS features as it has evolved too. Please look into:

process.hrtime() & NodeJS's other performance API hooks:

https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_timing_api

like image 24
Eric Hodonsky Avatar answered Sep 22 '22 16:09

Eric Hodonsky