我还是 Python 的新手,我一直在努力提高我的 Python 脚本的性能,所以我在使用和不使用全局变量的情况下对其进行了测试。我对它进行了计时,令我惊讶的是,它在声明全局变量而不是将局部变量传递给函数时运行得更快。这是怎么回事?我认为局部变量的执行速度更快? (我知道全局变量不安全,我还是很好奇。)
最佳答案
本地人应该更快
根据this page on locals and globals :
When a line of code asks for the value of a variable x, Python will search for that variable in all the available namespaces, in order:
- local namespace - specific to the current function or class method. If the function defines a local variable x, or has an argument x, Python will use this and stop searching.
- global namespace - specific to the current module. If the module has defined a variable, function, or class called x, Python will use that and stop searching.
- built-in namespace - global to all modules. As a last resort, Python will assume that x is the name of built-in function or variable.
基于此,我假设局部变量通常更快。我的猜测是您所看到的内容与您的脚本有关。
本地人更快
这是一个使用局部变量的简单示例,在我的机器上大约需要 0.5 秒(Python 3 中为 0.3):
def func():
for i in range(10000000):
x = 5
func()
还有全局版本,大约需要 0.7(Python 3 中为 0.5):
def func():
global x
for i in range(1000000):
x = 5
func()
global
对已经是全局的变量做了一些奇怪的事情
有趣的是,这个版本运行时间为 0.8 秒:
global x
x = 5
for i in range(10000000):
x = 5
虽然它在 0.9 中运行:
x = 5
for i in range(10000000):
x = 5
您会注意到,在这两种情况下,x
都是全局变量(因为没有函数),而且它们都比使用局部变量慢。我不知道为什么在这种情况下声明 global x
会有所帮助。
在 Python 3 中不会出现这种奇怪现象(两个版本都需要大约 0.6 秒)。
更好的优化方法
如果你想优化你的程序,你能做的最好的事情是profile it .这将告诉您什么花费的时间最多,因此您可以专注于此。你的流程应该是这样的:
- 打开分析运行您的程序。
- 查看 KCacheGrind 或类似程序中的配置文件以确定哪些函数花费的时间最多。
- 在这些函数中:
- 寻找可以缓存函数结果的地方(这样您就不必做太多工作)。
- 寻找算法改进,例如用封闭形式的函数替换递归函数,或用字典替换列表搜索。
- 重新配置文件以确保该功能仍然存在问题。
- 考虑使用 multiprocessing .
关于python - 全局变量与局部变量的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12590058/