PyORAm
[iotcloud.git] / PyORAM / src / pyoram / storage / AliTimer.py
1 import time
2
3
4
5
6 class Singleton:
7     """
8     A non-thread-safe helper class to ease implementing singletons.
9     This should be used as a decorator -- not a metaclass -- to the
10     class that should be a singleton.
11
12     The decorated class can define one `__init__` function that
13     takes only the `self` argument. Also, the decorated class cannot be
14     inherited from. Other than that, there are no restrictions that apply
15     to the decorated class.
16
17     To get the singleton instance, use the `Instance` method. Trying
18     to use `__call__` will result in a `TypeError` being raised.
19
20     """
21
22     def __init__(self, decorated):
23         self._decorated = decorated
24
25
26     def Instance(self):
27         """
28         Returns the singleton instance. Upon its first call, it creates a
29         new instance of the decorated class and calls its `__init__` method.
30         On all subsequent calls, the already created instance is returned.
31
32         """
33         try:
34             return self._instance
35         except AttributeError:
36             self._instance = self._decorated()
37             return self._instance
38
39
40
41     def __call__(self):
42         raise TypeError('Singletons must be accessed through `Instance()`.')
43
44     def __instancecheck__(self, inst):
45         return isinstance(inst, self._decorated)
46
47
48 @Singleton
49 class Foo:
50     def __init__(self):
51        print 'Foo created'
52        self._totalTime = 0;
53
54     def getTime(self):
55         return self._totalTime
56
57     def resetTimer(self):
58         self._totalTime = 0
59
60     def startTimer(self):
61         self._startTime = time.time()
62     
63     def endTimer(self):
64         self._totalTime += time.time() - self._startTime