Update: performance landed in the nodejs core! (version 9+)

So you’ve got a code path that you think might be running a little slowly — perhaps it’s a database call, or maybe a fun imagemagick transform. How do you instrument this event to observe and iterate on solutions to reduce latency?

Besides a more heavy-handed solution such as a profiling agent, the answer you might come up with is to simply log some high-resolution time metrics. Or to be direct: process.hrtime . Let’s take a look:

While you could use Date.now() in a similar fashion, process.hrtime is built expressly for these types of use cases. Also, hrtime gets you nanosecond resolution, whereas Date can only do millisecond.

Ok, so what do we do with this little array?

The first value indicates the number of seconds for the measure, and the next value the number of additional nanoseconds. So, if you’re like most humans and enjoy your metrics as a single value, you’ll have to do some MATH.

Alright, now we have a nice millisecond-formatted value to log or send to some third-party service. (8.2 seconds — you bad database, you)

So what does this look like applied as a whole?

Well alright, I suppose that will work. Slightly exhausting though isn’t it? And if you’ve got multiple repositories, duplicating the logic in extra places can be a drag. If you’re a DRY nut like I am, you’ll quickly want to mop this code up.

It’s at this point that I proclaim my undying love for the web, no matter how hostile, confusing, or just plain strange a platform to develop for it is. See, browsers have this nice little feature called the User Timing API (except for iOS — really?). It aims to tackle this exact type of problem by providing a more defined API with a central measure store.

Here’s an example:

That looks pretty nice! Shove your marks into a central data store and just call measure between the points you’re interested in later. Also, the duration values are automatically represented in milliseconds, or a DOMHighResTimeStamp if you prefer (would you though? really.)

As much as I love the web, I also love Node. And I feel like Node should have nice things too, right?

That’s why we at IOpipe created Performance Node, a package that aims to replicate and add features on top of the User Timing API.

Now it’s easy to loop through all the measurements and toss them into a datastore for analysis later! Internally the package uses good ole’ process.hrtime .

Is this the only way to create/digest this info? Nah. But it’s one way! And if you have experience with this particular web API, then you’ll feel right at home.

After NPM publish, we immediately put this lib to use in our Tracing Plugin and it’s working great! Please, let us know what you think.

https://github.com/iopipe/performance-node