javascript node.js 中的 console.time() 安全吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15348250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:29:23  来源:igfitidea点击:

Is console.time() safe in node.js?

javascriptnode.js

提问by stickfigure

I have a little snippet of node.js code in front of me that looks like this:

我面前有一小段 node.js 代码,如下所示:

console.time("queryTime");
doAsyncIOBoundThing(function(err, results) {
    console.timeEnd("queryTime");
    // Process the results...
});

And of course when I run this on my (otherwise idle) development system, I get a nice console message like this:

当然,当我在我的(否则空闲的)开发系统上运行它时,我会收到一条很好的控制台消息,如下所示:

queryTime: 564ms

However, if I put this into production, won't there likely be several async calls in progress simultaneously, and each of them will overwrite the previous timer? Or does node have some sort of magical execution context that gives each "thread of execution" a separate console timer namespace?

但是,如果我将其投入生产,是否会同时进行多个异步调用,并且每个调用都会覆盖前一个计时器?或者节点是否有某种神奇的执行上下文,为每个“执行线程”提供一个单独的控制台计时器命名空间?

回答by Zeta

Just use unique labels and it will be safe. That's why you use a label, to uniquely identify the start time.

只需使用独特的标签,它就会是安全的。这就是您使用标签来唯一标识开始时间的原因。

As long as you don't accidentally use a label twice everything will work exactly as intended. Also note that nodehas usually only one thread of execution.

只要您不意外地将标签使用两次,一切都会完全按预期工作。还要注意,node通常只有一个执行线程。

回答by Tal Tikotzki

Wouldn't this simple code work?

这么简单的代码不行吗?

var labelWithTime = "label " + Date.now();
console.time(labelWithTime);
// Do something
console.timeEnd(labelWithTime);

回答by Eric Hodonsky

Consider new NodeJS features as it has evolved too. Please look into:

考虑新的 NodeJS 特性,因为它也在发展。请查看:

process.hrtime()& NodeJS's other performance API hooks:

process.hrtime()& NodeJS 的其他性能 API 钩子:

https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_timing_api

https://nodejs.org/api/perf_hooks.html#perf_hooks_performance_timing_api