Python uses context to timing code snippets, non-adorners

Source: Internet
Author: User

Before a set of commonly used adorners, including a where_is_it_called adorner, can be timed and on the entry and return results, where the call to record, very powerful.

This is in context, the advantage of the context is that it does not require a function to be timed.

classTimercontextmanager (object):"""Timing With the context manager to time code snippets"""Log= Logmanager ('Timercontext'). Get_logger_and_add_handlers ()def __enter__(self): Self._line= Sys._getframe (). F_back.f_lineno#A function that calls the code of this methodSelf._file_name = Sys._getframe (1). F_code.co_filename#which file was tuned with this methodSelf.time_start =time.time ()def __exit__(self, exc_type, Exc_val, EXC_TB): T_spend= Time.time ()-Self.time_start Self.log.debug (f'timing The following code fragment: \ n Execute ' {self._file_name}:{self._line} ' with {t_spend} seconds')

Under test:

Python uses context to timing code snippets, non-adorners

Related Article

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.