Advertisement
lilo_booter

CPU Usage in Python

Jan 22nd, 2017
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.96 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import time
  4. import sys
  5.  
  6. def collect( ):
  7.     result = { }
  8.     fd = open( "/proc/stat" )
  9.     while True:
  10.         data = fd.readline( )
  11.         if data == '': break
  12.         if not data.startswith( "cpu" ): continue
  13.         key, delimiter, data = data.partition( " " )
  14.         result[ key ] = [ float( x ) for x in data.rstrip( ).split( ) ]
  15.     fd.close( )
  16.     return result
  17.  
  18. def process( first, second ):
  19.     result = { }
  20.     for key in first:
  21.         a = first[ key ]
  22.         b = second[ key ]
  23.         v1 = b[ 0 ] - a[ 0 ] + b[ 2 ] - a[ 2 ]
  24.         v2 = v1 + b[ 3 ] - a[ 3 ]
  25.         result[ key ] = 0
  26.         if v2 > 0:
  27.             result[ key ] = ( v1 * 100.0 ) / v2
  28.     return result
  29.  
  30. first = collect( )
  31. while True:
  32.     time.sleep( 0.1 )
  33.     second = collect( )
  34.     result = process( first, second )
  35.     for key in sorted( result.keys( ) ):
  36.         print result[ key ],
  37.     print
  38.     sys.stdout.flush( )
  39.     first = second
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement