ss4*_*153 7 python performance if-statement coding-style
if语句在这两种写作方式之间是否存在性能差异或风格偏好?基本上是一样的,1条件只会遇到一次,而其他条件会每隔一段时间遇到.如果只满足一次的条件是第一次还是第二次?性能明智吗?如果性能相同,我更喜欢第一种方式.
data = range[0,1023]
length = len(data)
max_chunk = 10
for offset in xrange(0,length,max_chunk):
chunk = min(max_chunk,length-offset)
if chunk < max_chunk:
write_data(data[offset:])
else:
write_data(data[offset:offset+max_chunk])
Run Code Online (Sandbox Code Playgroud)
VS
data = range[0,1023]
length = len(data)
max_chunk = 10
for offset in xrange(0,length,max_chunk):
chunk = min(max_chunk,length-offset)
if not chunk < max_chunk:
write_data(data[offset:offset+max_chunk])
else:
write_data(data[offset:])
Run Code Online (Sandbox Code Playgroud)
在您的示例中,if根本不需要:
data = range[0,1023]
length = len(data)
max_chunk = 10
for offset in xrange(0,length,max_chunk):
write_data(data[offset:offset+max_chunk]) # It works correctly
Run Code Online (Sandbox Code Playgroud)
我认为这是您案件中最有效的方式.
好吧,让我们试试:
x = np.random.rand(100)
def f(x):
z = 0
for i in x:
if i < 0.5:
z += 1
else:
z += 0
return z
def g(x):
z = 0
for i in x:
if not (i < 0.5):
z += 0
else:
z += 1
return z
Run Code Online (Sandbox Code Playgroud)
我们得到:
%timeit f(x)
10000 loops, best of 3: 141 us per loop
%timeit g(x)
10000 loops, best of 3: 140 us per loop
Run Code Online (Sandbox Code Playgroud)
不,这里没有太多差异.即使x较大,差异也很小.
我必须说我有点惊讶,我原本期望直接版本(f)比not版本(g)更有效.
道德:按你的喜好去做.
不应该有任何性能差异(如果有的话,我认为第二个性能会较差),但只需使用您更清楚的那个。我也更喜欢第一个。:)
如果您发现它稍后会产生影响,那么请继续更改它,但您知道他们所说的:过早的优化是万恶之源。