英文:
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('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");
<!-- end snippet -->
The same code runs on Node at repl.it.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论