Search code examples
javascriptnode.js

Writing a function to compute execution time in both Node and browser?


I'm trying to figure out how to write a clean function that is supported by both Node and the browser, but feel that the cleanliness of the solution is not as good as it could be.

Would it be hacky to have conditionals checking the presence of the window object?

if (typeof window !== undefined)
    // node computation
else 
    // browser computation

But I also want a clean way to compute the total execution time before and after some operation. How should I go about this?


Solution

  • The performance API is specified by a W3C recommendation and available in both Node and browsers.

    In Node you would need to include perf_hooks.

    Already with just performance.now() you can do basic timing operations:

    // Detect existance of `performance`. If not defined (Node), require it
    var performance = performance || require('perf_hooks').performance;
    
    let start = performance.now();
    
    let j = 1;
    for (let i = 0; i < 1000000; i++) j = j*2+1;
    
    console.log((performance.now() - start).toFixed(2) + "ms");

    The same code runs on Node.