Is it better to use an exception or a return code in Python?

后端 未结 6 2166
执念已碎
执念已碎 2020-12-13 06:08

You may know this recommendation from Microsoft about the use of exceptions in .NET:

Performance Considerations

...

Throw exc

6条回答
  •  庸人自扰
    2020-12-13 06:47

    I did a simple experiment to compare the performance of raising exceptions with the following code:

    from functools import wraps
    from time import time
    import logging
    
    def timed(foo):
        @wraps(foo)
        def bar(*a, **kw):
            s = time()
            foo(*a, **kw)
            e = time()
            print '%f sec' % (e - s)
        return bar
    
    class SomeException(Exception):
        pass
    
    def somefunc(_raise=False):
        if _raise:
            raise SomeException()
        else:
            return
    
    @timed
    def test1(_reps):
        for i in xrange(_reps):
            try:
                somefunc(True)
            except SomeException:
                pass
    
    @timed
    def test2(_reps):
        for i in xrange(_reps):
            somefunc(False)
    
    def main():
    
        test1(1000000)
        test2(1000000)
    
        pass
    
    if __name__ == '__main__':
        main()
    

    With the following results:

    • Raising exceptions: 3.142000 sec
    • Using return: 0.383000 sec

    Exceptions are about 8 times slower than using return.

提交回复
热议问题