How fast is your code?

ngduc

Duc Ng

Posted on October 4, 2018

How fast is your code?

One of the key metrics when writing code is speed. But there is no convenient way to measure the speed of your code efficiently so far. Chrome and other browsers do have APIs (new Date(), performance.now(), console.time) that let you put them around your code, then you will do a simple calculation to find out the diff, like: t2 - t1

Another Approach

That works for an instant need when you want to know how much time a block of code executes. However, when you want to do more, you will have to write some util functions or library.

Performance.now() is a high resolution timer API that you can rely on to measure time difference. Many modules were created to utilize that API, one of them is mstime - https://github.com/ngduc/mstime - a lightweight module (2 KB gzip) to measure and visualize code performance in (ms).

Usage

Now with the help of the mstime module, you can write simple code like this:

mstime.start("codeblock1");
myFunction();
console.log( mstime.end("codeblock1") );
Enter fullscreen mode Exit fullscreen mode

Nothing is new so far. Until you take a closer look a the output:

{
  entries: [
    { start: 41991120.53, end: 41991133.04, diff: 12.50 }
  ],
  plugins: { ... },
  last: 12.50,
  sum: 12.50,
  avg: 12.50
}
Enter fullscreen mode Exit fullscreen mode

That open the door to opportunities! You now have control on the dataset of every measurement, plus useful calculations like: sum, average (avg), last value & a plugin system!

There are a couple of built-in plugins like: calculating for trimmed mean (e.g. get 90 percentile of data), persisting data to localStorage, plotting data to chart, etc.

Example of using the chartist plugin to plot time data:

chartist plugin

Now it's your turn to utilize the dataset you captured!
Please comment below, let me know your ideas, feedbacks or anything you like to discuss.

💖 💪 🙅 🚩
ngduc
Duc Ng

Posted on October 4, 2018

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Fauda: configuration made simple
javascript Fauda: configuration made simple

November 25, 2020

I built my own static site generator.
javascript I built my own static site generator.

July 22, 2020

How fast is your code?
javascript How fast is your code?

October 4, 2018