简体   繁体   English

哪个是python中更好更快的方法?

[英]Which is the better & faster way in python?

Which way is faster in python? python中哪种方式更快?

if status=='Failed' or status=='Terminated' or status=='Aborted' or status=='Expired':
   break

or或者

if status in ['Failed', 'Terminated', 'Aborted', 'Expired']:
   break

The second one is slightly faster if you tend to fail the comparison in the first/second entry.如果您倾向于在第一个/第二个条目中进行比较失败,则第二个会稍快一些。 That's likely because the CONTAINS_OP is a single bytecode operation and goes into mostly-native code for iterating the list.这可能是因为CONTAINS_OP是单个字节码操作,并且主要是用于迭代列表的本机代码。 The first solution is checking each comparison in pure python which has some unnecessary overhead.第一个解决方案是在纯 python 中检查每个比较,这有一些不必要的开销。

But the difference is trivial and the overall time is usually ~0.3 μs per the whole check on my system, so it either shouldn't matter in practice, or the code should not use Python in the first place.但区别是微不足道的,每次在我的系统上进行整个检查,总时间通常约为 0.3 μs,因此在实践中应该无关紧要,或者代码首先不应该使用 Python。

You should test questions like that yourself.你应该自己测试这样的问题。 You can wrap your code in time checks:您可以在时间检查中包装您的代码:

def first(rep):
    status='foobar'
    for x in range(rep):
        if status=='Failed' or status=='Terminated' or status=='Aborted' or status=='Expired':
            pass

rep = 1000000
start = time.perf_counter()
first(rep)
diff1 = time.perf_counter()-start

and compare the results.并比较结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM