Python: Find out cpu time of a certain process
To find out how many percentage a certain process uses the cpu:
import os, time
# find out the pid by username.
# "-o pid h" omits the header and just prints the pid
pid = os.popen('ps -U my_user_name -o pid h').read().strip()
# 14th column is utime, 15th column is stime:
# The time the process has been scheduled in user/kernel mode
# The time value is in jiffies. One jiffie is appox 1/100 second
# see man proc for more info
stat = os.popen('cat /proc/%s/stat' % pid).read().strip()
cpu_time1=int(stat.split()[14]) + int(stat.split()[15])
time1=time.time()
time.sleep(1)
stat = os.popen('cat /proc/%s/stat' % pid).read().strip()
cpu_time2=int(stat.split()[14]) + int(stat.split()[15])
time2=time.time()
print str(float(cpu_time2 - cpu_time1) / (time2 - time1)) + "%"
I don’t know though if the number is accurate :)
What is “cpu time” anyway? It’s the time the process is running (using the cpu for 100%) divided by the time the process is laid asleep by the scheduler. Then, jiffies seem to be not a safe number for time measurements.
But for relative measurements it should do the trick.
Comments