tags:

views:

170

answers:

5

I was wondering why the try-except is slower than the if in the program below.

def tryway():
    try:
        while True:
            alist.pop()
    except IndexError:
        pass

def ifway():
    while True:
        if alist == []: 
            break
        else:
            alist.pop()
if __name__=='__main__':
    from timeit import Timer
    alist = range(1000)
    print "Testing Try"
    tr = Timer("tryway()","from __main__ import tryway")
    print tr.timeit()
    print "Testing If"
    ir = Timer("ifway()","from __main__ import ifway")
    print ir.timeit()

The results I get are interesting.

Testing Try
2.91111302376
Testing If
0.30621099472

Can anyone shed some light why the try is so much slower?

Thanks, James

A: 

Not sure but I think it's something like this: the while true follow the normal instruction line which means the processor can pipeline and do all sorts of nice things. Exceptions jump straight through all that so the VM need to handle it specially, and that takes time.

dutt
The way I looked at it was that if the when it's killing itself of the exception it's only checking at the end and then ending. Whereas the if look is testing the list 1000 times which I thought would be slower....
James
I think comparison against empty list is fairly quick, so it doesn't loose a lot of time doing it. Note, I'm not sure about these things, just thought I'd give you my line of thought.
dutt
+11  A: 

You're setting alist only once. The first call to "tryway" clears it, then every successive call does nothing.

def tryway():
    alist = range(1000)
    try:
        while True:
            alist.pop()
    except IndexError:
        pass

def ifway():
    alist = range(1000)
    while True:
        if alist == []:
            break
        else:
            alist.pop()
if __name__=='__main__':
    from timeit import Timer
    print "Testing Try"
    tr = Timer("tryway()","from __main__ import tryway")
    print tr.timeit(10000)
    print "Testing If"
    ir = Timer("ifway()","from __main__ import ifway")
    print ir.timeit(10000)

>>> Testing Try
>>> 2.09539294243
>>> Testing If
>>> 2.84440898895
Glenn Maynard
Thanks now I feel like an idiot :|
James
Beat me by about a minute. Oh well :P
Daenyth
James, if we had nothing to learn and never made silly mistakes, there'd be no reason for StackOverflow.
msw
+1  A: 

Exception handling is generally slow in most languages. Most compilers, interpreters and VMs (that support exception handling) treat exceptions (the language idiom) as exceptions (uncommon). Performance optimization involves trade-offs and making exceptions fast would typically mean other areas of the language would suffer (either in performance or simplicity of design).

At a more technical level, exceptions generally mean that the VM/interpretter (or the runtime execution library) has to save a bunch of state and begin pulling off all the state on the function call stack (called unwinding) up until the point where a valid catch (except) is found.

Or looking at it from a different viewpoint, the program stops running when an exception occurs and a "debugger" takes over. This debugger searches back through the stack (calling function data) for a catch that matches the exception. If it finds one, it cleans things up and returns control to the program at that point. If it doesn't find one then it returns control to the user (perhaps in the form of an interactive debugger or python REPL).

kanaka
This is pretty off-topic in the context of python. Exceptions in python are really cheap, and if the non-exceptional case it more common than the exception (as it should be), then it's going to be cheaper to try/catch than check -- as verified in Glenn's answer. EAFP > LBYL.
Daenyth
+2  A: 

If you are really interested in speed, both of your contestants could do with losing some weight.

while True: is slower than while 1: -- True is a global "variable" which is loaded and tested; 1 is a constant and the compiler does the test and emits an unconditional jump.

while True: is redundant in ifway. Fold the while/if/break together: while alist != []:

while alist != []: is a slow way of writing while alist:

Try this:

def tryway2():
    alist = range(1000)
    try:
        while 1:
            alist.pop()
    except IndexError:
        pass

def ifway2():
    alist = range(1000)
    while alist:
        alist.pop()

`

John Machin
While your comment about `True` is correct in the context of py 2.x, in py3k it's a real keyword and does not have that overhead.
Daenyth
+1  A: 

There is still faster way iterating with for, though sometimes we want list to physically shirink so we know how many are left. Then alist should be parameter to the generator. (John is also right for while alist:) I put the function to be a generator and used list(ifway()) etc. so the values are actualy used out of function (even not used):

def tryway():
    alist = range(1000)
    try:
        while True:
            yield alist.pop()
    except IndexError:
        pass

def whileway():
    alist = range(1000)
    while alist:
         yield alist.pop()

def forway():
    alist = range(1000)
    for item in alist:
         yield item

if __name__=='__main__':
    from timeit import Timer
    print "Testing Try"
    tr = Timer("list(tryway())","from __main__ import tryway")
    print tr.timeit(10000)
    print "Testing while"
    ir = Timer("list(whileway())","from __main__ import whileway")
    print ir.timeit(10000)
    print "Testing for"
    ir = Timer("list(forway())","from __main__ import forway")
    print ir.timeit(10000)

J:\test>speedtest4.py
Testing Try
6.52174983133
Testing while
5.08004508953
Testing for
2.14167694497
Tony Veijalainen