Python语句和函数之间的区别

时间:2018-07-27 02:38:09

标签: python performance

我目前正在使用python处理大量数据,但我有点好奇... 由于包含大量数据,因此代码速度真的很重要,因此,一些语句和执行此操作的函数之间是否有区别?

有什么区别
def my_function(var1):
    var2 = var1 + 1
    var3 = var1 - 1
    var4 = str(var1)
    print(var2, var3, var4)


for i in range(100000):
    my_function(i)

for i in range(100000):
    var1 = i
    var2 = var1 + 1
    var3 = var1 - 1
    var4 = str(var1)
    print(var2, var3, var4)

在谈论代码有多快时?

2 个答案:

答案 0 :(得分:1)

除非您在函数内几乎没有做任何事情,否则它很可能不会对您的代码产生任何可测量的影响。

说明:

In [1]: def spam(eggs):
   ...:     pass
   ...:
   ...:

In [2]: def a():
   ...:     for i in range(1000000):
   ...:         spam(i)
   ...:

In [3]: def b():
   ...:     for i in range(1000000):
   ...:         pass
   ...:

In [4]: %timeit a()
104 ms ± 3.53 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [5]: %timeit b()
25.9 ms ± 871 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

但是,如果代码实际上正在做某事,您将不再真正注意到它们之间的区别:

In [1]: def spam(eggs):
   ...:     return sum(x for x in range(eggs))
   ...:
   ...:

In [2]: def a():
   ...:     total = 0
   ...:     for i in range(1000):
   ...:         total += spam(i)
   ...:

In [3]: def b():
   ...:     total = 0
   ...:     for i in range(1000):
   ...:         total += sum(x for x in range(i))
   ...:

In [4]: %timeit a()
31 ms ± 1.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [5]: %timeit b()
31.8 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

也:过早的优化是万恶之源-DonaldKnuth

答案 1 :(得分:0)

在解释它时,存在很小的差异,但这取决于函数的大小,被调用多少次,正在做什么等。

对于已编译的Python代码,编译器通常足够聪明,可以将功能“解包”到其组件中进行优化。