I want to know the number of CPUs on the local machine using Python. The result should be user/real as output by time(1) when called with an optimally scaling userspace-only program.

解决方案

If you're interested into the number of processors available to your current process, you have to check cpuset first. Otherwise (or if cpuset is not in use), multiprocessing.cpu_count() is the way to go in Python 2.6 and newer. The following method falls back to a couple of alternative methods in older versions of Python:

import os

import re

import subprocess

def available_cpu_count():

""" Number of available virtual or physical CPUs on this system, i.e.

user/real as output by time(1) when called with an optimally scaling

userspace-only program"""

# cpuset

# cpuset may restrict the number of *available* processors

try:

m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$',

open('/proc/self/status').read())

if m:

res = bin(int(m.group(1).replace(',', ''), 16)).count('1')

if res > 0:

return res

except IOError:

pass

# Python 2.6+

try:

import multiprocessing

return multiprocessing.cpu_count()

except (ImportError, NotImplementedError):

pass

# https://github.com/giampaolo/psutil

try:

import psutil

return psutil.cpu_count() # psutil.NUM_CPUS on old versions

except (ImportError, AttributeError):

pass

# POSIX

try:

res = int(os.sysconf('SC_NPROCESSORS_ONLN'))

if res > 0:

return res

except (AttributeError, ValueError):

pass

# Windows

try:

res = int(os.environ['NUMBER_OF_PROCESSORS'])

if res > 0:

return res

except (KeyError, ValueError):

pass

# jython

try:

from java.lang import Runtime

runtime = Runtime.getRuntime()

res = runtime.availableProcessors()

if res > 0:

return res

except ImportError:

pass

# BSD

try:

sysctl = subprocess.Popen(['sysctl', '-n', 'hw.ncpu'],

stdout=subprocess.PIPE)

scStdout = sysctl.communicate()[0]

res = int(scStdout)

if res > 0:

return res

except (OSError, ValueError):

pass

# Linux

try:

res = open('/proc/cpuinfo').read().count('processor\t:')

if res > 0:

return res

except IOError:

pass

# Solaris

try:

pseudoDevices = os.listdir('/devices/pseudo/')

res = 0

for pd in pseudoDevices:

if re.match(r'^cpuid@[0-9]+$', pd):

res += 1

if res > 0:

return res

except OSError:

pass

# Other UNIXes (heuristic)

try:

try:

dmesg = open('/var/run/dmesg.boot').read()

except IOError:

dmesgProcess = subprocess.Popen(['dmesg'], stdout=subprocess.PIPE)

dmesg = dmesgProcess.communicate()[0]

res = 0

while '\ncpu' + str(res) + ':' in dmesg:

res += 1

if res > 0:

return res

except OSError:

pass

raise Exception('Can not determine number of CPUs on this system')

python虚拟cpu性能_如何使用python找出CPU数量相关推荐

  1. python 频繁项集_用FP-Growth算法找出销售数据中的频繁项集

    运行环境 python3.7.PyCharm 2018.2.4 (Community Edition) 数据来源 思路 从所给数据及其说明文档可以看出此数据集是从购物数据中收集而来的,每行数据都是一条 ...

  2. python调用jar 性能_亲自有效---python 调用jar

    #-*-coding:utf-8-*- import jpype from jpype import * import os.path jarpath = os.path.abspath('.') # ...

  3. python虚拟人脸生成_一个用StyleGAN训练出的黄种人人脸生成器

    黄种人人脸生成器 更新:基于StyleGAN2制作的新版生成器消除了生成图片中水滴斑点和扭曲/损坏现象的出现,质量大幅提升.点此查看新版. ------------------------------ ...

  4. python包括哪些部分_第一部分 Python基础篇

    第⼀一部分 Python基础篇 1. 为什什么学习Python? 朋友推荐,比较简单易学,生态圈比较强大 发展趋势:人工智能.数据分析 2. 通过什什么途径学习的Python? 廖雪峰.网络博客.相关 ...

  5. Top命令找出CPU占用较高的Java线程信息

    Top命令找出CPU占用较高的Java线程信息 由于种种原因导致生产环境的应用CPU占用奇高, 这个时候就需要确定到底是哪些线程占用了较高的CPU, 然后再做针对性的优化, 可以使用jconsole/ ...

  6. python虚拟cpu性能_基于Tensorflow:CPU性能分析

    iostat iostat用于输出CPU和磁盘I/O相关的统计信息. 命令格式: 1)显示所有设备负载情况 指令: iostat -m 2 5 cpu属性值说明: %user:CPU处在用户模式下的时 ...

  7. python 死循环程序能占满cpu吗_运行tensorflow python程序,限制对GPU和CPU的占用操作...

    一般情况下,运行tensorflow时,默认会占用可以看见的所有GPU,那么就会导致其它用户或程序无GPU可用,那么就需要限制程序对GPU的占用.并且,一般我们的程序也用不了所有的GPU资源,只是强行 ...

  8. python模块下载过程_常用的python模块及安装方法

    bsddb3:BerkeleyDB的连接组件 Cheetah-1.0:我比较喜欢这个版本的cheetah cherrypy:一个WEB framework ctypes:用来调用动态链接库 DBUti ...

  9. python彩票结果分析_天啦噜!Python多线程居然是骗人的?

    Python解释执行原理 我是一个Python线程,我的工作就是解释执行程序员编写的Python代码. 之所以说是解释执行,是因为Python是高级语言,CPU那家伙不认识Python代码,需要运行的 ...

最新文章

  1. jsp自定义图文新闻列表标签结合ssh2,带分页功能
  2. 自动ftp脚本的使用
  3. Two conferences重点词汇
  4. linux 动态执行cp,Linux常用命令之cp、mv、rm、cat、more、head、tail、ln命令讲解
  5. Shell入门(二)之变量
  6. 关于页面图表相应式的问题,问题遇见时间,9月1日,到今天9月2日,尚未解决...
  7. 2-字符串能否构成三角形及何种三角形
  8. gdb问题解决办法:no debugging symbols found
  9. acm竞赛使用python的多吗_我该参加acm竞赛吗?
  10. 清风老师数学建模笔记——层次分析法
  11. 解决 Cannot locate a 64-bit Oracle Client library 问题
  12. java设计模式之-策略模式
  13. winform工具1-图片去除水印
  14. 双十一有哪些电容笔值得入手?十大电容笔知名品牌
  15. 别人都在这个春暖花开的端午节吃粽子,而我在踏青学springboot数据持久化
  16. android SDK-25事件分发机制--源码正确解析
  17. idea快速开发之代码块编辑
  18. 集合面试题(谈谈你对集合的理解?)
  19. 计算机相关专业考研不考数学,2018考研不考数学的专业有哪些
  20. 罗永浩发布锤子手机系统 6月15日开放下载

热门文章

  1. 关于使用wcf架构分布式系统的一点想法
  2. 公司内部流量控制案例
  3. linux远程连接工具
  4. Python 工匠:善用变量来改善代码质量
  5. Java 基础 之 三目运算
  6. 【spring基础】spring 官方下载地址
  7. 阿里愚人节发布“如影计划”,黑科技让支付宝与掌心融为一体
  8. H5中滚动卡顿的问题
  9. 解决Bootstrap中代码不高亮问题
  10. 安卓之页面跳转与传值和按钮事件