Advertisement
Guest User

пример 4

a guest
Jul 22nd, 2013
483
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import psutil
  2. from time import time
  3.  
  4. def toggle(decorator):
  5.     """ позволить "подключать" и "отключать" декоратор """
  6.     def new_decorator(fn):
  7.         decorated = decorator(fn)
  8.  
  9.         def new_decorated(*x):
  10.             if decorator.enabled:
  11.                 return decorated(*x)
  12.             else:
  13.                 return fn(*x)
  14.  
  15.         return new_decorated
  16.  
  17.     decorator.enabled = True
  18.     return new_decorator
  19.  
  20. @toggle
  21. def timed(fn):
  22.     def decorated(*x):
  23.         start = time()
  24.         result = fn(*x)
  25.         print "Executing %s took %d ms" % (fn.__name__, (time()-start)*1000)
  26.         return result
  27.     return decorated
  28.  
  29. @toggle
  30. def repeat(times):
  31.     """ повторить вызов times раз, и вернуть среднее значение """
  32.     def decorator(fn):
  33.         def decorated2(*x):
  34.             total = 0
  35.             for i in range(times):
  36.                 total += fn(*x)
  37.             return total / times
  38.         return decorated2
  39.     return decorator
  40.  
  41. @timed
  42. @repeat(5)
  43. def cpuload():
  44.     load = psutil.cpu_percent()
  45.     print "cpuload() returns %d" % load
  46.     return load
  47.  
  48. print "cpuload.__name__==" + cpuload.__name__
  49. print "CPU load is %d%%" % cpuload()
  50. timed.enabled = False
  51. print "CPU load is %d%%" % cpuload()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement