Created
October 10, 2016 21:15
-
-
Save apahim/361c9358c69c93b87e926d296b49368a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import glob | |
import sys | |
cputopology="/sys/devices/system/cpu/" | |
def cores(): | |
return _csiblings / _tcratio | |
def threads(): | |
return _tsiblings / _tcratio | |
def sockets(): | |
return _phids | |
def _getThreads( cputopology): | |
""" | |
Get total threads for all cores. | |
""" | |
# If HT is enabled, return is a multiple of _getCores() | |
# If HT is disabled, return is the same number of _getCores() | |
kernelmap = [] | |
paths = glob.glob('/'.join([cputopology, | |
'cpu[0-9]*', 'topology/thread_siblings'])) | |
for path in paths: | |
with open(path) as f: | |
content = f.read().strip() | |
value = content.split('\n') | |
kernelmap.extend(value) | |
return _countKernelMapBits(kernelmap) | |
def _getCores( cputopology): | |
""" | |
Get total cores for all sockets. | |
""" | |
# If HT is enabled, _getCores() will include threads, | |
# since core_siblings file just born this way. | |
kernelmap = [] | |
paths = glob.glob('/'.join([cputopology, | |
'cpu[0-9]*', 'topology/core_siblings'])) | |
for path in paths: | |
with open(path) as f: | |
content = f.read().strip() | |
value = content.split('\n') | |
kernelmap.extend([item for item in value if item not in kernelmap]) | |
return _countKernelMapBits(kernelmap) | |
def _getSockets( cputopology): | |
""" | |
Get total sockets. | |
""" | |
ph_ids = [] | |
paths = glob.glob('/'.join([cputopology, | |
'cpu[0-9]*', 'topology/physical_package_id'])) | |
for path in paths: | |
with open(path) as f: | |
content = f.read().strip() | |
value = content.split('\n') | |
ph_ids.extend([item for item in value if item not in ph_ids]) | |
return len(ph_ids) | |
def _countKernelMapBits( kernelmap): | |
""" | |
Count bits 1 in a given kernel map. | |
""" | |
count = 0 | |
for i in kernelmap: | |
kmap = i.replace(',','') | |
# Converting from hex to dec | |
dec = int(kmap, 16) | |
while dec: | |
# Adding 1 into count when last bit is 1. | |
count += dec & 1 | |
# Droping last bit. | |
dec >>= 1 | |
return count | |
_phids = _getSockets(cputopology) | |
_csiblings = _getCores(cputopology) | |
_tsiblings = _getThreads(cputopology) | |
_tcratio = _tsiblings / _csiblings | |
if len(sys.argv) != 2: | |
print 'Choose between sockets, cores or threads' | |
sys.exit(1) | |
if sys.argv[1] == 'sockets': | |
print sockets() | |
elif sys.argv[1] == 'cores': | |
print cores() | |
elif sys.argv[1] == 'threads': | |
print threads() | |
else: | |
print 'Choose between sockets, cores or threads' | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment