python使用上下文对代码片段进行计时,非装饰器

之前发过了一组常用的装饰器,包括了一个where_is_it_called的装饰器,可以计时和对入参和返回结果,被何处调用进行记录,十分强大。

 

这是用上下文,上下文的好处是,不需要抽成函数才能计时。

 

class TimerContextManager(object):
    """
    用上下文管理器计时,可对代码片段计时
    """
    log = LogManager('TimerContext').get_logger_and_add_handlers()

    def __enter__(self):
        self._line = sys._getframe().f_back.f_lineno  # 调用此方法的代码的函数
        self._file_name = sys._getframe(1).f_code.co_filename  # 哪个文件调了用此方法
        self.time_start = time.time()

    def __exit__(self, exc_type, exc_val, exc_tb):
        t_spend = time.time() - self.time_start
        self.log.debug(f'对下面代码片段进行计时:  \n执行"{self._file_name}:{self._line}" 用时 {t_spend} 秒')

 

 

 测试下:

 

 

 

posted @ 2018-08-22 20:19  北风之神0509  阅读(280)  评论(2编辑  收藏  举报