Adr*_*rix 9 python optimization performance local-variables
从python的运行时效率角度来看,这些效率是否相等?
x = foo()
x = bar(x)
Run Code Online (Sandbox Code Playgroud)
VS
x = bar(foo())
Run Code Online (Sandbox Code Playgroud)
我有一个更复杂的问题,基本上可以归结为这个问题:显然,从代码长度的角度来看,第二个更为有效,但运行时是否也更好?如果不是,为什么不呢?
比较一下:
第一种情况:
%%timeit
def foo():
return "foo"
def bar(text):
return text + "bar"
def test():
x = foo()
y = bar(x)
return y
test()
#Output:
'foobar'
529 ns ± 114 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Run Code Online (Sandbox Code Playgroud)
第二种情况:
%%timeit
def foo():
return "foo"
def bar(text):
return text + "bar"
def test():
x = bar(foo())
return x
test()
#Output:
'foobar'
447 ns ± 34.6 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Run Code Online (Sandbox Code Playgroud)
但这只是针对每种情况运行一次%% timeit的比较。以下是每种情况下20次迭代的时间(以ns为单位的时间):
df = pd.DataFrame({'First Case(time in ns)': [623,828,634,668,715,659,703,687,614,623,697,634,686,822,671,894,752,742,721,742],
'Second Case(time in ns)': [901,786,686,670,677,683,685,638,628,670,695,657,698,707,726,796,868,703,609,852]})
df.plot(kind='density', figsize=(8,8))
Run Code Online (Sandbox Code Playgroud)
It was observed, with each iteration, the differences were diminishing. This plot shows that the performance difference isn't significant. From a readability perspective, the second case looks better.
In the first case, two expressions are evaluated: the first expression assigns the return value from foo() to x first and then the second expression calls bar() on that value. This adds some overhead. In the second case only one expression is evaluated, calling both functions at once and returning the value.
| 归档时间: |
|
| 查看次数: |
186 次 |
| 最近记录: |