在 JavaScript 中获取 CPU 核心数?

发布于 2024-09-10 18:16:48 字数 68 浏览 1 评论 0原文

有没有办法确定 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

猫腻 2024-09-17 18:16:48

是的。引用MDN:

navigator.hardwareConcurrency 只读属性返回可用于在用户计算机上运行线程的逻辑处理器的数量...

现代计算机的 CPU 中有多个物理处理器核心(典型的是两个或四个核心),但每个物理核心通常也能够使用高级调度技术一次运行多个线程。例如,四核 CPU 可以提供八个逻辑处理器核心。逻辑处理器核心的数量可用于测量无需上下文切换即可有效运行的线程数量。

但是,浏览器可能会选择报告较低数量的逻辑核心,以便更准确地表示可以同时运行的 Worker 数量,因此不要将此视为对核心数量的绝对测量用户的系统。

现在除了 Internet Explorer 之外的所有浏览器都支持它。为了与旧版浏览器兼容,或者为了绕过对此参数解析的误导性浏览器隐私限制,您可以使用polyfill 核心估计器演示博客文章)。

Yes. To quote MDN:

The navigator.hardwareConcurrency read-only property returns the number of logical processors available to run threads on the user's computer…

Modern computers have multiple physical processor cores in their CPU (two or four cores is typical), but each physical core is also usually able to run more than one thread at a time using advanced scheduling techniques. So a four-core CPU may offer eight logical processor cores, for example. The number of logical processor cores can be used to measure the number of threads which can effectively be run at once without them having to context switch.

The browser may, however, choose to report a lower number of logical cores in order to represent more accurately the number of Workers that can run at once, so don't treat this as an absolute measurement of the number of cores in the user's system.

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).

夏日落 2024-09-17 18:16:48

不,没有,除非您使用某些 ActiveX。

No, there isn't, unless you use some ActiveX.

只等公子 2024-09-17 18:16:48

这是我一起编写的一个相当快的并发估计器...它还没有经过太多测试:

http://jsfiddle .net/Ma4YT/2/

这是工作人员运行的代码(因为我有一个 jsfiddle 链接,因此需要示例):


// create worker concurrency estimation code as blob
var blobUrl = URL.createObjectURL(new Blob(['(',
  function() {
    self.addEventListener('message', function(e) {
      // run worker for 4 ms
      var st = Date.now();
      var et = st + 4;
      while(Date.now() < et);
      self.postMessage({st: st, et: et});
    });
  }.toString(),
')()'], {type: 'application/javascript'}));

估计器有大量工作人员在短时间内运行(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):


// create worker concurrency estimation code as blob
var blobUrl = URL.createObjectURL(new Blob(['(',
  function() {
    self.addEventListener('message', function(e) {
      // run worker for 4 ms
      var st = Date.now();
      var et = st + 4;
      while(Date.now() < et);
      self.postMessage({st: st, et: et});
    });
  }.toString(),
')()'], {type: 'application/javascript'}));

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.

苹果你个爱泡泡 2024-09-17 18:16:48

如果您要对工作人员进行数据处理,navigator.hardwareConcurrency 可能不够好,因为它返回现代浏览器中的逻辑核心数量,您可以尝试使用以下方法来估计物理核心数量WebCPU

import {WebCPU} from 'webcpu';

WebCPU.detectCPU().then(result => {
    console.log(`Reported Cores: ${result.reportedCores}`);
    console.log(`Estimated Idle Cores: ${result.estimatedIdleCores}`);
    console.log(`Estimated Physical Cores: ${result.estimatedPhysicalCores}`);
});

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:

import {WebCPU} from 'webcpu';

WebCPU.detectCPU().then(result => {
    console.log(`Reported Cores: ${result.reportedCores}`);
    console.log(`Estimated Idle Cores: ${result.estimatedIdleCores}`);
    console.log(`Estimated Physical Cores: ${result.estimatedPhysicalCores}`);
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文