Skip to content

Instantly share code, notes, and snippets.

@uranusjr
Created March 17, 2012 10:08
Show Gist options
  • Save uranusjr/2057296 to your computer and use it in GitHub Desktop.
Save uranusjr/2057296 to your computer and use it in GitHub Desktop.
Get CPU usage in %
import time
def cpuUsage():
with open('/proc/stat', 'r') as statFile:
cpuValues = [int(v) for v in statFile.readline().strip().split()[1:]]
total1 = sum(cpuValues)
work_1 = sum(cpuValues[0:3])
time.sleep(2) # Sample 2 seconds
with open('/proc/stat', 'r') as statFile:
cpuValues = [int(v) for v in statFile.readline().strip().split()[1:]]
total2 = sum(cpuValues)
work_2 = sum(cpuValues[0:3])
return (float(work_2 - work_1) / (total2 - total1))
if __name__ == '__main__':
print 'CPU usage in last 2 seconds:', cpuUsage() * 100, '\b%'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment