You will be able to measure time using with. It can be used when measuring time with Kaggle etc.
Used in Mercari Competition 1st Code ..
Just write @contextmanager just before defining the function you want to use as the context manager.
When timer is called, the initial time is stored in t0, and yeild exits the temporary function. After the processing of time.sleep (1) is completed, it returns to timer again and outputs the difference from the initial time.
qiita.rb
from contextlib import contextmanager
import time
@contextmanager
def timer(name):
t0 = time.time()
print("start")
yield
print("end")
print(f'[{name}] done in {time.time() - t0:.0f} s')
with timer('process train'):
time.sleep(1)
If @contextmanager is not described, timer cannot operate as contextmanager and an error will occur.
[with minutes and context manager] (https://docs.python.org/ja/3/reference/datamodel.html#context-managers "Qiita") The context manager handles the entry and exit processing required to execute a block of code.
As shown in the following example, the context manager class describes the process for starting and the process for ending. Therefore, if you make it a context manager with @contextmanager, timer will be called at the start and end. If @contextmanager is not described, an error occurs because enter is not defined. Reference
Recommended Posts