Enhance the efficiency of time tracking function

I have been using a nodejs module to track the execution time of different parts of my application.

// polyfill for window.performance.now
var performance = global.performance || {}
var performanceNow =
  performance.now        ||
  performance.mozNow     ||
  performance.msNow      ||
  performance.oNow       ||
  performance.webkitNow  ||
  function(){ return (new Date()).getTime() }

// generate timestamp or delta
// see http://nodejs.org/api/process.html#process_process_hrtime
function hrtime(previousTimestamp){
  var clocktime = performanceNow.call(performance)*1e-3
  var seconds = Math.floor(clocktime)
  var nanoseconds = Math.floor((clocktime%1)*1e9)
  if (previousTimestamp) {
    seconds = seconds - previousTimestamp[0]
    nanoseconds = nanoseconds - previousTimestamp[1]
    if (nanoseconds<0) {
      seconds--
      nanoseconds += 1e9
    }
  }
  return [seconds,nanoseconds]
}

function timer(start) {
    if ( !start ) return hrtime();
    var end = hrtime(start);
    return Math.round((end[0]*1000) + (end[1]/1000000));
}

module.exports = timer;

Using this module is simple: time = benchmark(); to start tracking, and time = benchmark(time); to measure the duration since the last call.

A workaround has been added for browser compatibility when needed for my application.

While the function does its job effectively, it ironically impacts performance significantly, especially in Internet Explorer.

I am looking for ways to optimize it for better speed.

Answer №1

You are performing numerous additional calculations...

// A polyfill for window.performance.now
var performance = global.performance || {}
var performanceNow =
  performance.now        ||
  performance.mozNow     ||
  performance.msNow      ||
  performance.oNow       ||
  performance.webkitNow  ||
  function(){ return (new Date()).getTime() }

function clock(start) {
    if ( !start ) return performanceNow();
    var end = performanceNow();
    return end - start;
}

module.exports = clock;

This code is designed to produce the same outcomes. (Without using Math.round)

All methods (performance.now & Date.getTime) provide time in milliseconds. As per my understanding, this is the expected output.

In some browsers like Chrome, performance now may give an additional sub-millisecond time component, which would result in a non-integer returned value

For example:

> performance.now()
160693.10000000405

Additionally, you can test the performance of time retrieval methods:

In Chrome on my computer, Date.now() shows maximum speed, tripling the output of performance.now()

Refer to https://jsperf.com/get-time-3482/1 for more details

          Date.now    performance.now
Chrome    10 MOps      3.5 MOps
Safari    10 MOps      7   MOps

If you run multiple tests or measure large time intervals, the extra nanosecond precision may not be necessary

In such cases, consider using IE9+ compatible code:

var now = Date.now;
function clock(start) {
    if ( !start ) return now();
    var end = now();
    return end - start;
}

module.exports = clock;

=====

Additional information:

The performance of performance.now vs Date.now could vary based on Intel and AMD CPUs

These methods utilize different processor instructions for time retrieval, refer to for more insights

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The selector is present, but I am unable to retrieve information about the node since the specified selector does not correspond to any node within the DOM tree

Working on building an E2E test using NodeJS and TestCafe. We recently integrated BrowserStack for cross-browser testing, focusing on Windows7:firefox & Windows10:firefox. However, encountering failures only when running scripts in this specific confi ...

Issue with Passport Google Oauth login redirection to successful route

I am currently following a tutorial on setting up Google Oauth in my Express app using Passport.js. The tutorial can be found here. Below are the routes defined in my server.js file: // Code snippet here The server.js file also imports configurations fro ...

The present user who is currently logged into the stackmob platform

I am currently working on retrieving a list of contacts for the logged-in user, but I am struggling to identify the current user. In Parse.com, you would use Parse.User.current(), but I am unsure if Stackmob offers a similar functionality. Below is the co ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

I'm interested in knowing if it's feasible to develop unique jQuery selectors that can navigate ancestors, such as a :closest or :parents selector

As a developer who frequently creates jQuery plugins, I often find myself using custom jQuery selectors like :focusable and :closeto to simplify common filters in my code. For example, the :focusable selector is defined as follows: jQuery.extend(jQuery.e ...

What is the best way to address Peer dependency alerts within npm?

Here is a sample package.json that I am using for my application: dependencies : { P1 : “^1.0.0” // with peer dependency of p3 v1 P2 : “^1.0.0” // with peer dependency of p3 v2 } P1 and P2 both have peer dependencies on ...

Implementing a Tab on Firefox Extension Upon Window Load

I have a requirement to add a tab whenever a new Firefox window is loaded for my bootstrap extension. Below is the code snippet I am using: var WindowListener = { setupBrowserUI: function(window) { window.gBrowser.selectedTab=window.gBrowser.a ...

Tips for transferring localstorage values from the view to the controller in order to utilize them as a PHP variable in a separate view

How can I pass the value from local storage as a PHP variable when using location.href in the controller after clicking a button? In the view: echo Html::button('Proceed', [ 'onclick' => " var dataVal = localStorage.g ...

Establishing a connection with Taffy DB using Node.js

Currently, I am in the process of developing an application that utilizes Angular js, Node js, and Taffy DB. The main challenge I am facing involves storing the data submitted from the front-end into Taffy DB through the Node js server. var express = req ...

Filtering Quantity Based on Specific Attribute in ReactJs

I want to implement a quantity filter that can be based on color, size, or both. For instance, when I select the red color, it should display the total quantity of red items available. However, if I choose both the color red and size small, it should show ...

Secure access in Node.js and Express.js

I have successfully implemented login page authentication using the passport local strategy in my project. A portion of the code from users.js that handles this is shown below: router.post('/login', passport.authenticate('local', ...

Eliminate any properties with values that exceed the specified number in size

:) I'm trying to create a function that removes properties with values greater than a specified number. I've searched through multiple resources like this question on how to remove properties from a JavaScript object and this one on removing pro ...

"Exploring the implementation of error handling in Node.js Connect framework - where to begin

When attempting to utilize the errorhandler in my nodejs application, I am not seeing any difference in behavior whether it is used or not. I am seeking guidance on how to effectively implement the errorhandler module in nodejs. var app = connect(); if ...

The request method 'PUT' is not currently supported

Currently, I am working on a project that involves springboot, angularjs, and restful services. Here is my REST controller: @RequestMapping(value="/updatestructure/{ch}", method = RequestMethod.PUT) public @ResponseBody Structurenotification updateStruct ...

What could be causing my page width to only expand to 100% when using "fit-content"?

After searching extensively, I'm unable to find a solution that fits my current issue. My goal is to construct a practice ecommerce website using React. One of the components I have is a header which I'd like to occupy 100% of the screen width, c ...

Encountered a problem while trying to run expo build:ios on a Windows machine for a React

Currently, I am working on developing an IOS edition of my React Native App using Expo CLI. However, during the process, I came across the following error: error Has anyone faced this particular issue in the past? While the Android version of my app was ...

Utilizing Vue to send information to the POST function

I am encountering an issue with passing data to the Vue.js post method. I am using vue-resource and according to the documentation, it should be structured like this: this.$http.post('/someUrl', [body], [options]).then(successCallback, errorCall ...

Troubleshooting VueJs and vue-i18n issues

Currently, I am utilizing the Webpack CLI Template. As a next step, I proceed to install using the command npm install --save vue-i18n Within my main.js file, I undertake the necessary importation and configuration by setting the locale to "en" import ...

Node.js application for changing attributes in an HTML string

Within my node.js backend, there exists an object with a specific property named content, which stores an HTML string. The content within includes an img tag that currently has a src attribute containing a base64 string. I am seeking to modify this src att ...

Unable to load the manually added module in the /node_modules/ folder

I'm trying to manually use a module that I placed in the /node_modules/ directory. After copying and pasting the files and installing dependencies with npm, I encountered an issue while using NWJS 0.16.0. When attempting var speech = require('sp ...