简体   繁体   English

Node.js上性能繁重的算法

[英]Performance heavy algorithms on Node.js

I'm creating some algorithms that are very performance heavy, eg evolutionary and artificial intelligence. 我正在创建一些非常重要的算法,例如进化和人工智能。 What matters to me is that my update function gets called often (precision), and I just can't get setInterval to update faster than once per millisecond. 对我来说重要的是我的更新函数经常被调用(精度),而我无法让setInterval以每毫秒一次的速度更新。

Initially I wanted to just use a while loop, but I'm not sure that those kinds of blocking loops are a viable solution in the Node.js environment. 最初我想使用while循环,但我不确定那些阻塞循环是Node.js环境中可行的解决方案。 Will Socket.io's socket.on("id", cb) work if I run into an "infinite" loop? 如果我遇到“无限”循环,Socket.io的socket.on(“id”,cb)会起作用吗? Does my code somehow need to return to Node.js to let it check for all the events, or is that done automatically? 我的代码是否需要返回Node.js以检查所有事件,还是自动完成?

And last (but not least), if while loops will indeed block my code, what is another solution to getting really low delta-times between my update functions? 最后(但并非最不重要),如果while循环确实会阻止我的代码,那么在我的更新函数之间获得非常低的delta时间的另一个解决方案是什么? I think threads could help, but I doubt that they're possible, my Socket.io server and other classes need to somehow communicate, and by "other classes" I mean the main World class, which has an update method that needs to get called and does the heavy lifting, and a getInfo method that is used by my server. 我认为线程可以提供帮助,但我怀疑它们是否可行,我的Socket.io服务器和其他类需要以某种方式进行通信,而“其他类”我的意思是主要的World类,它有一个需要获取的更新方法调用并执行繁重的工作,以及我的服务器使用的getInfo方法。 I feel like most of the time the program is just sitting there, waiting for the interval to fire, wasting time instead of doing calculations... 我觉得大多数时候程序只是坐在那里,等待间隔开火,浪费时间而不是做计算......

Also, I'd like to know if Node.js is even suited for these sorts of tasks. 另外,我想知道Node.js是否适合这些类型的任务。

You can execute havy algorithms in separate thread using child_process.fork and wait results in main thread via child.on('message', function (message) { }); 您可以使用child_process.fork在单独的线程中执行havy算法,并通过child.on('message', function (message) { });在主线程中等待结果child.on('message', function (message) { });

app.js app.js

var child_process = require('child_process');
var child = child_process.fork('./heavy.js', [ 'some', 'argv', 'params' ]);
child.on('message', function(message) {
     // heavy results here
});

heavy.js heavy.js

while (true) {
    if (Math.random() < 0.001) {
        process.send({ result: 'wow!' });
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM