1

How do you detect the number of CPU cores in crystal?

In Go you can do runtime.NumCPU() and in Node.js you can do os.cpus(). Is there something similar in Crystal?

Sam Eaton
  • 1,795
  • 1
  • 14
  • 19

2 Answers2

2

The last time I checked (admittedly that was long ago) there was no direct way to do that, but you can get access to this information through the command line. I ended up combining multiple of these answers for redundancy.

THREADS = `getconf _NPROCESSORS_ONLN || nproc --all || grep -c '^processor' /proc/cpuinfo`.to_i
Oleh Prypin
  • 33,184
  • 10
  • 89
  • 99
0

Use System.cpu_count. This will give you the number of logical cores available. This method was introduced in Crystal 0.23.0.

Here's the source for it in the tree for Crystal 0.29.0: https://github.com/crystal-lang/crystal/blob/fbfe8b62f44eca4596090b7580801bd184f73c7a/src/system.cr#L22

taylorthurlow
  • 2,953
  • 3
  • 28
  • 42