如何检测 Crystal 中的 CPU 个核心数?

How to detect number of CPU cores in Crystal?

如何检测 crystal 中的 CPU 个核心数?

在 Go 中,您可以执行 runtime.NumCPU(),在 Node.js 中,您可以执行 os.cpus()。 Crystal中有类似的东西吗?

我上次查看(诚然那是很久以前的事了)没有直接的方法,但您可以通过命令行访问此信息。我最终合并了 these answers 的倍数以实现冗余。

THREADS = `getconf _NPROCESSORS_ONLN || nproc --all || grep -c '^processor' /proc/cpuinfo`.to_i

使用System.cpu_count。这将为您提供可用的逻辑核心数。此方法在 Crystal 0.23.0.

中介绍

这是 Crystal 0.29.0 树中的来源:https://github.com/crystal-lang/crystal/blob/fbfe8b62f44eca4596090b7580801bd184f73c7a/src/system.cr#L22