相关疑难解决方法(0)

Python如果vs try-except

我想知道为什么try-except比下面的程序中的if慢.

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()
Run Code Online (Sandbox Code Playgroud)

我得到的结果很有趣.

Testing Try
2.91111302376
Testing If
0.30621099472
Run Code Online (Sandbox Code Playgroud)

任何人都可以解释为什么尝试这么慢?

python performance

25
推荐指数
1
解决办法
1万
查看次数

标签 统计

performance ×1

python ×1