`#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()

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.

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

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

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

ReplyDelete