Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Single Process CPU Usage
def get_current_cpu(pid):
d = open("/proc/%s/stat" % pid, "r").readline().split()
return int(d[13]), int(d[14])
def get_total_cpu():
d = open("/proc/stat", "r").readline()
return sum(map(int, d.split()[1:]))
def main(argv):
import time
pid = int(argv[1])
wait = int(argv[2])
cpu_before = get_current_cpu(pid)
total_before = get_total_cpu()
cpu_after = get_current_cpu(pid)
total_after = get_total_cpu()
total_diff = total_after - total_before
cuserp = 100 * (cpu_after[0] - cpu_before[0]) / total_diff
csysp = 100 * (cpu_after[1] - cpu_before[1]) / total_diff
print cuserp
print csysp
if __name__ == '__main__':
import sys
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment