forked from alspitz/python_utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtimed.py
More file actions
47 lines (37 loc) · 891 Bytes
/
timed.py
File metadata and controls
47 lines (37 loc) · 891 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import time
class Timed:
""" This fails if methods are accessed but not called! """
def __getattribute__(self, name):
if name in ['_time_dict', '__getattr__']:
return object.__getattribute__(self, name)
if not hasattr(self, '_time_dict'):
self._time_dict = {}
d = self._time_dict
if callable(object.__getattribute__(self, name)):
now = time.time()
if name in d:
self.dt = now - d[name]
else:
self.dt = None
d[name] = now
return object.__getattribute__(self, name)
if __name__ == "__main__":
class Test(Timed):
def __init__(self):
self.x = 0
def inc(self):
self.x += 1
print("inc", self.dt)
def dec(self):
self.x -= 1
print("dec", self.dt)
t = Test()
t.dec()
t.inc()
t.inc()
time.sleep(0.5)
t.inc()
time.sleep(0.2)
t.inc()
print(t.x)
t.dec()