-
-
Notifications
You must be signed in to change notification settings - Fork 33.2k
Closed as not planned
Labels
type-featureA feature request or enhancementA feature request or enhancement
Description
Feature or enhancement
Proposal:
Hello everybody.
I have a suggestion :
I frequently use this class to measure computation times
# import time
class Timer:
def __init__(self, text:str="", prompt=True, r=2):
self.text = text
self.prompt = prompt
self.r = r
def __enter__(self):
self.tic = time.time()
if self.prompt :
print(self.text, end=' ... ', flush=True)
return self.__call__
def __exit__(self ,type, value, traceback):
self.toc = time.time()
if self.prompt:
print('Done in ', str(round(self.toc-self.tic, self.r)), ' s.', flush=True)
def __call__(self):
return self.toc-self.tic
This allows me to follow computation operations and retrieve execution times easily within my code, with a context manager, as in the following :
with Timer('computing things') as t:
time.sleep(1) # Do computations here
exec_time = t()
This also makes the measurement robust to exceptions raising, and allows to get the execution time before the exception was raised.
Basically I never use the time module in another way than with this class, setting "prompt=False" if I want it silent and "r" being the rounding number to display time.
Hence I think this might be a simple built-in class of the "time" module, so my suggestion is to add it (or something similar) (or in another module).
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Metadata
Metadata
Assignees
Labels
type-featureA feature request or enhancementA feature request or enhancement