您当前的位置:首页 > 计算机 > 软件应用 > 开发工具(IDE)

在 Emacs 中获取 CPU 核的数量

时间:12-14来源:作者:点击数:
CDSY,CDSY.XYZ

在 linux/cygwin下获取 CPU 核的数量

linux/cygwin 提供了 /proc 虚拟文件系统可以获取系统信息,具体来说,在 /proc/cpuinfo 中会列出所有 CPU 核的信息

(when (file-exists-p "/proc/cpuinfo")
  (with-temp-buffer
    (insert-file-contents "/proc/cpuinfo")
    (how-many "^processor[[:space:]]+:")))
2

在 Windows 下获取 CPU 核的数量

Windows 提供了一个名为 NUMBER_OF_PROCESSORS 的环境变量,里面存的就是核的数量

(let ((number-of-processors (getenv "NUMBER_OF_PROCESSORS")))
  (when number-of-processors
    (string-to-number number-of-processors)))

在 BSD/OSX 下获取 CPU 核的数量

需要调用 sysctl 来获取

(with-temp-buffer
  (ignore-errors
    (when (zerop (call-process "sysctl" nil t nil "-n" "hw.ncpu"))
      (string-to-number (buffer-string)))))

综合起来

通过变量 system-type 可以获得操作系统的类型,不同操作系统调用不同的方法来获取 CPU 核的数量

(defun numcores ()
  "Return number of cores"
  (case system-type
    ((gnu/linux cygwin)
     (when (file-exists-p "/proc/cpuinfo")
       (with-temp-buffer
         (insert-file-contents "/proc/cpuinfo")
         (how-many "^processor[[:space:]]+:")))
     )
    ((gnu/kfreebsd darwin)
     (with-temp-buffer
       (ignore-errors
         (when (zerop (call-process "sysctl" nil t nil "-n" "hw.ncpu"))
           (string-to-number (buffer-string)))))
     )
    ((windows-nt)
     (let ((number-of-processors (getenv "NUMBER_OF_PROCESSORS")))
       (when number-of-processors
         (string-to-number number-of-processors)))
     )))
CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐