Number of processors/cores in command line

2019-01-30 01:49发布

I am running the following command to get the number of processors/cores in Linux:

cat /proc/cpuinfo | grep processor | wc -l

It works but it does not look elegant. How would you suggest improve it ?

10条回答
萌系小妹纸
2楼-- · 2019-01-30 02:36

If you need an os independent method, works across Windows and Linux. Use python

$ python -c 'import multiprocessing as m; print m.cpu_count()'
16
查看更多
Ridiculous、
3楼-- · 2019-01-30 02:39
倾城 Initia
4楼-- · 2019-01-30 02:39

On newer kernels you could also possibly use the the /sys/devices/system/cpu/ interface to get a bit more information:

$ ls /sys/devices/system/cpu/
cpu0  cpufreq  kernel_max  offline  possible  present  release
cpu1  cpuidle  modalias    online   power     probe    uevent
$ cat /sys/devices/system/cpu/kernel_max 
255
$ cat /sys/devices/system/cpu/offline 
2-63
$ cat /sys/devices/system/cpu/possible 
0-63
$ cat /sys/devices/system/cpu/present 
0-1
$ cat /sys/devices/system/cpu/online 
0-1

See the official docs for more information on what all these mean.

查看更多
Luminary・发光体
5楼-- · 2019-01-30 02:40

If you want to do this so it works on linux and OS X, you can do:

CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)
查看更多
登录 后发表回答