Skip to content

Commit c1bd688

Browse files
authored
Merge pull request #643 from katex35/patch-9
Create timer_gokay_sahin.py
2 parents 8288b11 + 34b3160 commit c1bd688

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Week06/timer_gokay_sahin.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
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)

0 commit comments

Comments
 (0)