【问题标题】:How to profile exception handling in Python?如何在 Python 中分析异常处理?
【发布时间】:2013-12-28 10:43:21
【问题描述】:

有没有办法找出有多少异常被抛出(和捕获)以及异常处理花费了多少时间?

我正在使用pyparsing(稍作修改),它严重依赖异常,我想了解(或至少估计)是否值得努力重写它以使其在没有异常的情况下工作。

异常的引发和捕获广泛分布在模块中,所以我正在寻找一种不需要修改每个 try-except-block 的方法

【问题讨论】:

    标签: python profiling


    【解决方案1】:

    当您想要分析代码时,使用上下文管理器可能是个好主意

    import time
    from contextlib import contextmanager
    
    # global
    NUMBER_OF_EXCEPTIONS = 0
    
    # define the timer
    class Timer(object):
        def __init__(self):
            self.t1 = time.time()
        def stop(self):
            self.t2 = time.time()
            self.elapsed = self.t2 - self.t1
    
    # define the profiler
    @contextmanager
    def profiler():
        t = Timer()
        yield t
        t.stop()
        print("elapsed: ", t.elapsed)
    
    # use the profiler!
    with profiler():
        try:
            1/0
        except ZeroDivisionError:
            # handle exception
            NUMBER_OF_EXCEPTIONS += 1
            time.sleep(1.1)
    
    # and use it again!
    with profiler():
        try:
            1/2
        except ZeroDivisionError:
            # handle exception
            NUMBER_OF_EXCEPTIONS += 1
            time.sleep(1.1)
    
    print("Total handled exceptions: ", NUMBER_OF_EXCEPTIONS)
    

    输出应该是这样的:

    elapsed:  1.10120511055
    elapsed:  4.05311584473e-06
    Total handled exceptions:  1
    

    现在,如果您想变得更花哨,您也可以编写上下文管理器来处理您的异常 (source)。这种技术可以产生非常干净的代码:

    NUMBER_OF_EXCEPTIONS = 0
    
    @contextmanager
    def handle_zero_division_error():
        try:
            yield
        except ZeroDivisionError as err:
            global NUMBER_OF_EXCEPTIONS
            NUMBER_OF_EXCEPTIONS += 1
            time.sleep(1.1)
    
    with profiler():
        with handle_zero_division_error():
            1/0
    
    with profiler():
        with handle_zero_division_error():
            1/0
    
    # you can even write it like this
    with profiler(), handle_zero_division_error():
        1/2
    
    print("Total handled exceptions: ", NUMBER_OF_EXCEPTIONS)
    

    还有输出:

    elapsed:  1.10123705864
    elapsed:  1.10085892677
    elapsed:  1.90734863281e-05
    Total handled exceptions:  2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多