Created
March 17, 2012 10:08
-
-
Save uranusjr/2057296 to your computer and use it in GitHub Desktop.
Get CPU usage in %
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
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