gpt4 book ai didi

Python 语句和函数的区别

转载 作者:行者123 更新时间:2023-12-01 09:12:21 28 4
gpt4 key购买 nike

我目前正在使用 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)

当谈论代码有多快时?

最佳答案

它很可能不会对您的代码产生任何可测量的影响,除非您在函数内部几乎没有执行任何操作。

举例说明:

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

关于Python 语句和函数的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51549997/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com