Skip to content

Commit 87648fa

Browse files
authored
Merge pull request #649 from icelal-kskn/master
Create timer_ikram_celal_keskin.py
2 parents c1bd688 + feeab99 commit 87648fa

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

Week06/timer_ikram_celal_keskin.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
import time
2+
import logging
3+
4+
5+
6+
7+
class Timer:
8+
"""
9+
Timer class that measures the time taken by the block of code it manages.
10+
It is a context manager class that can be used with the 'with' statement.
11+
It logs the start time, end time and the elapsed time of the block of code it manages.
12+
13+
14+
:param start_time: The time when the timer is started
15+
:type start_time: float
16+
:param end_time: The time when the timer is ended
17+
:type end_time: float
18+
19+
"""
20+
def __init__(self):
21+
""" Initializes the start_time and end_time of the Timer class """
22+
self.start_time = None
23+
self.end_time = None
24+
25+
def __enter__(self):
26+
""" Logs the start time of the Timer class and caller module """
27+
self.start_time=time.time()
28+
logging.info("--------------------Timer started-------------------")
29+
logging.info(f"Timer called by {__name__} module")
30+
return self
31+
32+
def __exit__(self,execution_type = None, execution_value=None, traceback=None)-> float:
33+
""" Logs the end time of the Timer class and calculates the elapsed time of the block of code it manages """
34+
self.end_time=time.time()
35+
36+
if execution_type or execution_value or traceback:
37+
logging.error(Exception(f"An error occured during the exiting of the {__name__} module"))
38+
logging.info("--------------------Timer stopped-------------------")
39+
return False
40+
41+
time_taken = self.end_time-self.start_time
42+
logging.info(f"Elapsed time of {__name__} module is {time_taken} seconds")
43+
logging.info("--------------------Timer stopped-------------------")
44+
return time_taken
45+
46+
47+

0 commit comments

Comments
 (0)