Sure, here’s the translation: 写一个函数来计算在Node.js和浏览器中的执行时间?

huangapple go评论87阅读模式
英文:

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?

英文:

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

得分: 4

performance API由W3C建议规定,并在Node和浏览器中都可用。

在Node中,您需要包含perf_hooks

仅使用performance.now(),您就可以进行基本的定时操作:

// 检测是否存在`performance`。如果未定义(在Node中),则需要引入它
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");

相同的代码在Node上运行,链接在repl.it上。

英文:

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:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

// Detect existance of `performance`. If not defined (Node), require it
var performance = performance || require(&#39;perf_hooks&#39;).performance;

let start = performance.now();

let j = 1;
for (let i = 0; i &lt; 1000000; i++) j = j*2+1;

console.log((performance.now() - start).toFixed(2) + &quot;ms&quot;);

<!-- end snippet -->

The same code runs on Node at repl.it.

huangapple
  • 本文由 发表于 2020年1月6日 23:49:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615067.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定