Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import psutil
- from time import time
- def toggle(decorator):
- """ позволить "подключать" и "отключать" декоратор """
- def new_decorator(fn):
- decorated = decorator(fn)
- def new_decorated(*x):
- if decorator.enabled:
- return decorated(*x)
- else:
- return fn(*x)
- return new_decorated
- def enable():
- decorator.enabled = True
- def disable():
- decorator.enabled = False
- new_decorator.enable = enable
- new_decorator.disable = disable
- enable()
- return new_decorator
- @toggle
- def timed(fn):
- def decorated(*x):
- start = time()
- result = fn(*x)
- print "Executing %s took %d ms" % (fn.__name__, (time()-start)*1000)
- return result
- return decorated
- @toggle
- def repeat(times):
- """ повторить вызов times раз, и вернуть среднее значение """
- def decorator(fn):
- def decorated2(*x):
- total = 0
- for i in range(times):
- total += fn(*x)
- return total / times
- return decorated2
- return decorator
- @timed
- @repeat(5)
- def cpuload():
- load = psutil.cpu_percent()
- print "cpuload() returns %d" % load
- return load
- print "cpuload.__name__==" + cpuload.__name__
- print "CPU load is %d%%" % cpuload()
- timed.disable()
- print "CPU load is %d%%" % cpuload()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement