Search code examples
pythontry-catchexecution

how measure execution with try/except bad used


Sorry about my english. I need scrit to show the right use of try/except in Python. I try the rigth and wrong way and wait for more time execution in the wrong way, but I can't prove that. I'm beginer with python. I think only those lines that generate exceptions need to be in try block, n=1000000 will not generate an exception, I know, but is only for testing under the same conditions. Regards. Daniel

from time import time
#**************************
#Right use, I suppose
#**************************
start1=time()
try:
    n=1000000
except:
     print('Error en el ingreso')  
while n>=0: #out try is more fast?
       n-=1 #out try is more fast?
end1=time()#end mark good time
good=end1-start1
print('Time right used: {}'.format(good))
#**************************
#Wrong use, I suppose
#**************************
start2=time()
try: 
    n=1000000
    while n>=0:#in try is more slow?
       n-=1    #in try is more slow?
except:
    print('Error en el ingreso')         
end2=time()
bad=end2-start2#end mark bad time
print('Time wrong used: {}'.format(bad))

if bad>=good:
    print('Bad use take more time')
else:
    print('Good use take more time')

Solution

  • Some things to note:

    • time.time() returns the "wall-clock" time. This is a bad metric to use when benchmarking code. What you want to measure is how much time the CPU took to complete the code. For this you can use the timeit module.
    • When benchmarking, try to write the smallest representative code that takes short time to run, so that you can execute it a lot of times and take the average (using timeit).

    On to the example:

    from timeit import timeit
    
    def loop_with_tryexcept():
        try:
            n = 10_000
            while n >= 0:
                n -= 1
        except:
            print("Error")
    
    def loop_without_tryexcept():
        n = 10_000
        while n >= 0:
            n -= 1
    
    
    """
    python -i test.py
    
    >>> timeit('loop_with_tryexcept()', setup='from __main__ import loop_with_tryexcept', number=1000)
    0.49678000000017164
    >>> timeit('loop_without_tryexcept()', setup='from __main__ import loop_without_tryexcept', number=1000)
    0.5228376000000026
    
    # It seems a tiny bit faster. Or is it?
    
    
    >>> timeit('loop_with_tryexcept()', setup='from __main__ import loop_with_tryexcept', number=1000)
    0.4899204999999256
    >>> timeit('loop_without_tryexcept()', setup='from __main__ import loop_without_tryexcept', number=1000)
    0.4767956000000595
    
    # Nope, it was just randomness introduced by the CPU.
    """
    

    You can see there is no difference in speed when wrapping code in a try/except block.