Python uses the with context to implement the timing function, and python Context

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.