20

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?

stickfigure
  • 13,458
  • 5
  • 34
  • 50

3 Answers3

36

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.

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • Interesting thing about this (maybe), you can actually pass an object as a label, and if you define a `toString` method it will be used and the returned value will be printed. This has to do with the `String` constructor. – travis Mar 11 '13 at 21:14
  • While this is true, how would you access the same object a second time? You _could_ use a JSON and c/p it, however then you have two objects to maintain. Or you save the object in a variable. But in this case, you could have simply used the variable's name as label… – Zeta Mar 11 '13 at 21:17
  • 4
    @travis: But be careful: any occurrence of `this._times[label]` will implicitly call your `toString` method. So that method has to be consistent (for a given object, it has to give the same result every time), *and* it has to be unique (it has to give different results for different objects). So I think you're best off just using strings. – ruakh Mar 11 '13 at 21:17
12

Wouldn't this simple code work?

var labelWithTime = "label " + Date.now();
console.time(labelWithTime);
// Do something
console.timeEnd(labelWithTime);
vp_arth
  • 14,461
  • 4
  • 37
  • 66
Tal Tikotzki
  • 373
  • 3
  • 7
7

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

Eric Hodonsky
  • 5,617
  • 4
  • 26
  • 36