js中检测和测量事件循环阻塞

js中检测和测量事件循环阻塞

本文介绍了如何在Node.js中检测和测量事件循环阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想监视node.js中事件循环的每次运行需要多长时间.但是,我不确定衡量这一点的最佳方法.我想出的最好方法是这样的:

I'd like to monitor how long each run of the event loop in node.js takes. However I'm uncertain about the best way to measure this. The best way I could come up with looks like this:

var interval = 500;
var interval = setInterval(function() {
    var last = Date.now();
    setImmediate(function() {
        var delta = Date.now() - last;
        if (delta > blockDelta) {
            report("node.eventloop_blocked", delta);
        }
    });
}, interval);

我基本上是通过查看setInterval的延迟来推断事件循环运行时间的.在 blocked 节点模块中,我已经看到了相同的方法,但是感觉不准确且繁重.有没有更好的方法来获取这些信息?

I basically infer the event loop run time by looking at the delay of a setInterval. I've seen the same approach in the blocked node module but it feels inaccurate and heavy. Is there a better way to get to this information?

更新:由hapi.js完成,将代码更改为使用setImmediate.

Update: Changed the code to use setImmediate as done by hapi.js.

推荐答案

是否有更好的方法来获取此信息?"我没有比检查SetImmediate的时间延迟更好的方法来测试事件循环,但是您可以使用节点的高分辨率计时器而不是Date.now()

"Is there a better way to get this information?"I don't have a better way to test the eventloop than checking the time delay of SetImmediate, but you can get better precision using node's high resolution timer instead of Date.now()

var interval = 500;
var interval = setInterval(function() {
    var last = process.hrtime();          // replace Date.now()
    setImmediate(function() {
        var delta = process.hrtime(last); // with process.hrtime()
        if (delta > blockDelta) {
            report("node.eventloop_blocked", delta);
        }
    });
}, interval);

注意:增量将是一个元组数组[秒,纳秒].

NOTE: delta will be a tuple Array [seconds, nanoseconds].

有关process.hrtime()的更多详细信息: https://nodejs.org/api/all.html#all_process_hrtime

For more details on process.hrtime():https://nodejs.org/api/all.html#all_process_hrtime

主要用途是测量间隔之间的效果."

"The primary use is for measuring performance between intervals."

这篇关于如何在Node.js中检测和测量事件循环阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 17:04