简体   繁体   中英

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?

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.

Wouldn't this simple code work?

var labelWithTime = "label " + Date.now();
console.time(labelWithTime);
// Do something
console.timeEnd(labelWithTime);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM