简体   繁体   English

int> 0比!= 0快吗?

[英]Is >0 faster than !=0 for an int?

Which test is faster : equality or inequality ? 哪个测试更快:平等还是不平等?

For example, in a big while loop, should the condition be a>0 rather than a!=0 ? 例如,在一个大的while循环中,条件应该是a>0而不是a!=0吗?

When asking yourself a question about speed differences between different operators, use the timeit module to measure . 当问自己一个关于不同操作员之间的速度差异的问题时,请使用timeit模块进行测量 They are equally fast: 它们同样快:

>>> import timeit
>>> timeit.timeit('a > 0', 'a = 1', number=10**7)
0.2486400604248047
>>> timeit.timeit('a > 0', 'a = 0', number=10**7)
0.2411360740661621
>>> timeit.timeit('a != 0', 'a = 1', number=10**7)
0.24765801429748535
>>> timeit.timeit('a != 0', 'a = 0', number=10**7)
0.24990510940551758

That's the comparisons repeated 10 million times, and if you re-run the above tests you'll find the timings can vary somewhat and none are clear winners. 就是说,这种比较重复了1000万次,如果重新运行上述测试,您会发现时间安排可能会有所不同,而且没有明显的赢家。

You should be focusing on readability here, not speed. 您应该在此处重点关注可读性,而不是速度。 A simple integer comparison is going to be an infinitesimal part of your overall execution speed, even in a loop. 即使在循环中,简单的整数比较也将是整体执行速度的无穷小部分。

If we're talking about a being an int , then on my machine at this very moment, an equality check is very slightly faster than a greater-than check. 如果我们谈论的是a是一个int在这个非常时刻,然后我的机器上,一个平等的检查比大于检查非常稍快。 You can quickly check that yourself using the timeit module : 您可以使用timeit模块快速检查自己:

>>> for s in 'a = 2', 'a = 0', 'a = -2':
        timeit('a != 0', s)
        timeit('a > 0', s)

0.06030992519848155
0.06666935212976455
0.053299842422489974
0.06516424110179742
0.05866621696540619
0.06685335186756447

However , those numbers are super close to another. 但是 ,这些数字非常接近另一个数字。 So you should only take one thing out of this answer: It does not matter . 因此,您应该仅从此答案中取一件事: 没关系

These kind of things are micro optimizations. 这些都是微优化。 And micro optimizations very rarely have any impact on the real performance of an application. 微观优化很少会对应用程序的实际性能产生任何影响。 It is a lot more likely that there are thousand other parts in your application that have more impact on the performance to make this difference negligible. 您的应用程序中还有数千个其他部分对性能的影响更大,以致这种差异可以忽略不计。 You should only care about such things if you actually profiled your application and confirmed that this part of your code is a bottleneck that is taking down the performance of your application. 仅当您实际分析了应用程序并确认代码的这一部分是导致应用程序性能下降的瓶颈时,才应该关心这些事情。 But for this particular code, I doubt that will ever be the case. 但是对于这个特定的代码,我怀疑情况是否会如此。

So please, don't bother about these minor difference but just use whatever makes more sense : Considering that these two checks have a different semantic meaning (a number being unequal to zero, or a number being larger than zero), choose the one that you actually meant to check for. 因此,请不要理会这些微小的差异,而只是使用更有意义的方法 :考虑到这两项检查具有不同的语义含义(一个数字不等于零,或者一个数字大于零),请选择一个您实际上要检查。

For me, timeit doesn't show any consistently noticeable difference (assuming you're working with integers)... 对我来说, timeit并没有显示出任何明显的差异(假设您使用的是整数)...

>>> timeit.timeit('1 > 0')
0.031796932220458984
>>> timeit.timeit('1 != 0')
0.03249096870422363
>>> timeit.timeit('1 > 0')
0.03250718116760254
>>> timeit.timeit('1 != 0')
0.031616926193237305

As stated in the comments on this question, rather than focusing on what operator is the fastest, you should focus on the one that makes the most sense. 正如对此问题的评论中所述,您应该专注于最有意义的运营商,而不是专注于最快的运营商。 If you really mean "do this while a is greater than 0 " than use > . 如果您真正的意思是“在a大于0执行此操作”,请使用use > The amount of time spent doing this comparison is going to be a very minor contributor to your overall runtime, so it probably isn't worth worrying which operator is faster... 进行比较所花费的时间对整个运行时的贡献很小,因此不必担心哪个运算符会更快...

Is it the bottleneck of your program? 这是您程序的瓶颈吗? Only if the answer is yes, you should be worried about it . 只有答案是肯定的,您才应该担心它 Moreover, there is not something that says this will be sure faster in any OS, or with any type. 而且,没有什么可以确保在任何操作系统或任何类型的操作系统中都能确保更快的速度。


For fun, I timed the while loop: 为了好玩,我定时了while循环:

#!/usr/bin/python
import time

a = 1000000
t0 = time.time()
while(a != 0):
    a = a - 1
t1 = time.time()

total = t1-t0
print total

and: 和:

a > 0 gives: a > 0给出:

0.12652015686 0.12652015686

a != 0 gives: a != 0给出:

0.111998081207 0.111998081207


For timing, check this: How can I time a code segment for testing performance with Pythons timeit? 对于计时,请检查以下内容: 如何计时代码段以使用Python的timeit测试性能?


But , use timeit , as Martijn Pieters suggested ( Get time of execution of a block of code in Python 2.7 ), like this: 但是 ,请使用Martijn Pieters建议的timeit获取在Python 2.7中执行代码块的时间 ),如下所示:

#!/usr/bin/python

import timeit
a = 1000000
start_time = timeit.default_timer()
while(a != 0):
    a = a - 1
elapsed = timeit.default_timer() - start_time
print elapsed

which gave for a > 0 : 给出a > 0

0.10852098465 0.10852098465

and for a != 0 : 对于a != 0

0.108459949493 0.108459949493

See the difference in the two timing approaches! 看看两种计时方法的区别!

I think this somewhat leaden test program shows in the case of character and integer compares there is basically no difference 我认为这个有点领先的测试程序在字符和整数比较的情况下显示出基本上没有区别

import string
def numericgtmostfail():
    for i in range(100):
        x= i > 99
    return x

def numericgtmostsucceed():
    for i in range(100):
        x= i > 1
    return x

def numericnemostsucceed():
    for i in range(100):
        x= i != 99
    return x

def numericnemostfail():
    for i in range(100):
        x= i != i
    return x

def chgtmostfail():
    for s in (string.lowercase * 4)[0:100]:
        x = s > 'y'
    return x

def chgtmostsucceed():
    for s in (string.lowercase * 4)[0:100]:
        x = s > 'a'
    return x

def chnemostfail():
    for s in (string.lowercase * 4)[0:100]:
        x = s != s 
    return x

def chnemostsucceed():
    for s in (string.lowercase * 4)[0:100]:
        x = s != 'a' 
    return x

if __name__ == '__main__':
    import timeit
    print(timeit.timeit("numericgtmostfail()", setup="from __main__ import numericgtmostfail"))
    print(timeit.timeit("numericgtmostsucceed()", setup="from __main__ import numericgtmostsucceed"))
    print(timeit.timeit("numericnemostsucceed()", setup="from __main__ import numericnemostsucceed"))
    print(timeit.timeit("numericnemostfail()", setup="from __main__ import numericnemostfail"))
    print(timeit.timeit("chgtmostfail()", setup="from __main__ import chgtmostfail"))
    print(timeit.timeit("chgtmostsucceed()", setup="from __main__ import chgtmostsucceed"))
    print(timeit.timeit("chnemostsucceed()", setup="from __main__ import chnemostsucceed"))
    print(timeit.timeit("chnemostfail()", setup="from __main__ import chnemostfail"))

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

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