0

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?

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

7 Comments

Do I need to conditionally use this based on Node or browser in the code? I'm seeing Module not found: Error: Can't resolve 'perf_hooks' and I'm requiring performance in from that module.
Indeed, you need to conditionally require perf_hook. The condition is whether you have performance defined or not yet. I update my answer, including a link to repl.it where you can see the same code run on Node.
I'm still getting "Error: Can't resolve 'perf_hooks' " for some reason, even though it's a native node module. Any reason for this? I'm using webpack
What's your Node version?
10.15 is the version using node -v
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.