在 JavaScript 中获取 CPU 核心数?
有没有办法确定 JavaScript 中可用 CPU 核心的数量,以便您可以根据该数量调整 Web Worker 的数量?
Is there a way to determine the number of available CPU cores in JavaScript, so that you could adjust the number of web workers depending on that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的。引用MDN:
现在除了 Internet Explorer 之外的所有浏览器都支持它。为了与旧版浏览器兼容,或者为了绕过对此参数解析的误导性浏览器隐私限制,您可以使用polyfill
核心估计器
(演示,博客文章)。Yes. To quote MDN:
It's now supported by every browser except Internet Explorer. For compatibility with older browsers, or to bypass misguided browser privacy restrictions on the resolution of this parameter, you can use the polyfill
core-estimator
(demo, blog post).不,没有,除非您使用某些 ActiveX。
No, there isn't, unless you use some ActiveX.
您可以尝试使用以下方法估计核心数量:
https://github.com/oftn/core-estimator
演示:
http://eligrey.com/blog/post/cpu-core-estimation -with-javascript
You can try to estimate the number of cores with:
https://github.com/oftn/core-estimator
demo:
http://eligrey.com/blog/post/cpu-core-estimation-with-javascript
这是我一起编写的一个相当快的并发估计器...它还没有经过太多测试:
http://jsfiddle .net/Ma4YT/2/
这是工作人员运行的代码(因为我有一个 jsfiddle 链接,因此需要示例):
估计器有大量工作人员在短时间内运行(4毫秒)并报告回到它们运行的时间(不幸的是,在 Web Workers 中 Performance.now() 无法获得更准确的计时)。然后主线程检查同一时间内运行的最大工作线程数。该测试会重复多次,以获得合适的样本来进行估计。
因此,主要思想是,给定足够小的工作量,只有在有足够的核心支持该行为的情况下,才应该安排工作人员同时运行。这显然只是一个估计,但到目前为止,对于我测试过的几台机器来说,它相当准确——这对于我的用例来说已经足够好了。可以增加样本数量以获得更准确的近似值;我只使用 10,因为它很快,而且我不想把时间浪费在估计上而不是仅仅完成工作上。
Here's a fairly quick concurrency estimator I hacked together... it hasn't undergone much testing yet:
http://jsfiddle.net/Ma4YT/2/
Here's the code the workers run (since I have a jsfiddle link a sample is necessary):
The estimator has a large number of workers run for a short period of time (4ms) and report back the times that they ran (unfortunately, performance.now() is unavailable in Web Workers for more accurate timing). The main thread then checks to see the maximum number of workers that were running during the same time. This test is repeated a number of times to get a decent sample to produce an estimate with.
So the main idea is that, given a small enough chunk of work, workers should only be scheduled to run at the same time if there are enough cores to support that behavior. It's obviously just an estimate, but so far it's been reasonably accurate for a few machines I've tested -- which is good enough for my use case. The number of samples can be increased to get a more accurate approximation; I just use 10 because it's quick and I don't want to waste time estimating versus just getting the work done.
如果您要对工作人员进行数据处理,
navigator.hardwareConcurrency
可能不够好,因为它返回现代浏览器中的逻辑核心数量,您可以尝试使用以下方法来估计物理核心数量WebCPU:If you are going to do data crunching on your workers,
navigator.hardwareConcurrency
might not be good enough as it returns the number of logical cores in modern browsers, you could try to estimate the number of physical cores using WebCPU: