Python uses the with context to implement the timing function, and python Context
Introduction
The with statement is a feature related to Exception Handling introduced from Python 2.5 (in Python 2.5, it can be used only after being imported from _ ure _ import with_statement ), available by default from version 2.6 (refer to What's new in Python 2.6? ). The with statement is applicable to resource access. Make sure that the necessary "clean" operation is performed to release resources no matter whether exceptions occur during use, for example, the file is automatically closed after use, and the lock in the thread is automatically obtained and released.
In Python, you often need to record how long a piece of code has been running. Generally, twotime.time()
And then calculate the difference value. The advanced one is to write a timer decorator and wrap the method with the decorator to record the running time, but this means that your code needs to be written in the function, this time decorator can then be used.
Today, I want to introduce a Python timing method that can timing a piece of code, rather than a convenient and "advanced" function timing method.
The Code is as follows:
from contextlib import contextmanager@contextmanagerdef timer(name): start = time.time() yield print(f'[{name}] done in {time.time() - start:.2f} s')
Usage:
with timer('Test'): i = 0 while i < 1000000: i += 1
Output:
[Test] done in 0.11 s
Adding from 1 to 1 million requires 0.11 s. You can modify the time precision in timer by modifying. 2f.
Summary
The above section describes how to use the with context to implement the timing function in Python. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!