Friday, February 6, 2009

Python CPU Usage

I recently needed to obtain the CPU usage in a Pythonic-way. After some searching, I found this example. I've adapted it to fit my needs and to fit a more general purpose usage. Here is my version of the example.
#Python CPU usage example.

import time

class CPUsage:
def __init__(self, interval=0.1, percentage=True):
self.interval=interval
self.percentage=percentage
self.result=self.compute()

def get_time(self):
stat_file=file("/proc/stat", "r")
time_list=stat_file.readline().split(" ")[2:6]
stat_file.close()
for i in range(len(time_list)) :
time_list[i]=int(time_list[i])
return time_list

def delta_time(self):
x=self.get_time()
time.sleep(self.interval)
y=self.get_time()
for i in range(len(x)):
y[i]-=x[i]
return y

def compute(self):
t=self.delta_time()
if self.percentage:
result=100-(t[len(t)-1]*100.00/sum(t))
else:
result=sum(t)
return result

def __repr__(self):
return str(self.result)

if __name__ == "__main__":
print CPUsage()
Here, we have a class called CPUsage. This class is capable of getting the CPU usage as a percentage or in milliseconds. This is specified by the percentage constructor parameter. The interval constructor parameter specifies the length of time we are measuring. This defaults to 0.1 seconds. Finally, the constructor invokes the compute() method to store the result.

The get_time() method will return a list of CPU numbers needed to compute the number of milliseconds the CPU has been in use for the interval we are measuring.

The delta_time() method will accept a time list returned by the get_time() method. It will then return the delta time based on the same list format.

The compute() method will calculate the percentage of CPU usage or simply return the CPU time.

To me, this makes for a more object-oriented approach. This class can also be modified to suite a different usage scenario.

3 comments :

  1. The time.clock() function returns the same information, but in a cross-platform way that doesn't involve /proc.

    ReplyDelete
  2. The time.clock() function shows the cpu usage of the python script, not the global cpu usage.

    ReplyDelete
  3. You could use comprehensions to make the end of a couple of your functions more readable - otherwise very useful - thanks!

    ReplyDelete