File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed
Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 1+ import time
2+
3+ class Timer :
4+ """
5+ A context manager to measure the time taken for a block of code to execute.
6+
7+ Attributes:
8+ start_time (float): The start time of the code block.
9+ end_time (float): The end time of the code block.
10+ """
11+
12+ def __init__ (self ):
13+ """
14+ Initializes the Timer class with start_time and end_time set to 0.
15+ """
16+ self .start_time = 0
17+ self .end_time = 0
18+
19+ def __enter__ (self ):
20+ """
21+ Starts the timer.
22+
23+ Returns:
24+ Timer: Returns the Timer instance with start_time set to the current time.
25+ """
26+ self .start_time = time .time ()
27+ return self
28+
29+ def __exit__ (self , * kwargs ):
30+ """
31+ Stops the timer by setting end_time to the current time.
32+ """
33+ self .end_time = time .time ()
34+
35+ if __name__ == "__main__" :
36+ with Timer () as timer :
37+ print (timer .start_time )
38+ time .sleep (2 )
39+ print (timer .end_time )
You can’t perform that action at this time.
0 commit comments