SHOW:
|
|
- or go back to the newest paste.
| 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 |
| 17 | + | def enable(): |
| 18 | decorator.enabled = True | |
| 19 | def disable(): | |
| 20 | decorator.enabled = False | |
| 21 | new_decorator.enable = enable | |
| 22 | new_decorator.disable = disable | |
| 23 | enable() | |
| 24 | return new_decorator | |
| 25 | ||
| 26 | @toggle | |
| 27 | def timed(fn): | |
| 28 | def decorated(*x): | |
| 29 | start = time() | |
| 30 | result = fn(*x) | |
| 31 | print "Executing %s took %d ms" % (fn.__name__, (time()-start)*1000) | |
| 32 | return result | |
| 33 | return decorated | |
| 34 | ||
| 35 | @toggle | |
| 36 | def repeat(times): | |
| 37 | """ повторить вызов times раз, и вернуть среднее значение """ | |
| 38 | def decorator(fn): | |
| 39 | def decorated2(*x): | |
| 40 | total = 0 | |
| 41 | for i in range(times): | |
| 42 | total += fn(*x) | |
| 43 | return total / times | |
| 44 | return decorated2 | |
| 45 | return decorator | |
| 46 | ||
| 47 | @timed | |
| 48 | @repeat(5) | |
| 49 | def cpuload(): | |
| 50 | - | timed.enabled = False |
| 50 | + | |
| 51 | print "cpuload() returns %d" % load | |
| 52 | return load | |
| 53 | ||
| 54 | print "cpuload.__name__==" + cpuload.__name__ | |
| 55 | print "CPU load is %d%%" % cpuload() | |
| 56 | timed.disable() | |
| 57 | print "CPU load is %d%%" % cpuload() |