python - Python中全局变量和局部变量的速度

标签 python optimization global-variables local-variables

我想每个人都知道:

Python accesses local variables much more efficiently than global variables

好的,这是真的:

oldlist = [str(i) for i in range(500)]
oldlist1 = [i for i in range(500)]

%%timeit
newlist = []
for word in oldlist:
    newlist.append(word.upper())

10000 次循环,最好的 3 次:每次循环 178 微秒

%%timeit
def func():
    newlist = []
    for word in oldlist:
        newlist.append(word.upper())
    return newlist
newlist = func()

10000 次循环,最好的 3 次:每次循环 93.2 µs

不幸的是,看起来这不是全局规则而是特例:

%%timeit
newlist = []
for nr in oldlist1:
    newlist.append(nr * nr)

10000 次循环,最好的 3 次:每次循环 60.3 µs

%%timeit
def func():
    newlist = []
    for nr in oldlist1:
        newlist.append(nr * nr)
    return newlist
newlist = func()

10000 次循环,最好的 3 次:每次循环 60.5 微秒

如何解释这些测试?

最佳答案

在上一个示例中,您首先定义了一个额外的函数。如果您在找到函数后启动计时器,它应该会更快。

关于python - Python中全局变量和局部变量的速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20075044/

相关文章:

python - 使用上下文管理器将脚本输出重定向到文件?

python - 从文件中读取数字列表的最快方法

matlab - "relative global"matlab或其他语言的变量

LISP 在局部函数中更改全局变量值

javascript - 如何在模块脚本中声明全局变量

python JSON只获取第一级的键

python - 如何规范化tensorflow中的数据

python - 将可变大小的字节数组转换为整数/长整数

php - Flex w/AMF 返回结果缓慢

algorithm - 最优和差