Python timeit 函数崩溃,出现 NameError: global name does not exist

2024-09-29 19:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在python2.7中对两个可比较的语句进行基准测试。你知道吗

一条语句打印从内存中检索的数字列表。另一条语句打印从同一服务器上维护的redis列表中检索到的相同号码的列表。你知道吗

例如

pylist1 = [1,2,3,4,5]
pylist2 = my_server.lrange("nums:5",0,-1) #where nums:5 = [1,2,3,4,5]

如何使用timeit对print pylist1print pylist2进行基准测试?你知道吗

我正在python shell中尝试以下操作:

import timeit
import redis
POOL = redis.ConnectionPool(host='127.0.0.1',port=6379,db=0)
my_server = redis.Redis(connection_pool=POOL)
pylist1 = [1,2,3,4,5]
pylist2 = my_server.lrange("nums:5",0,-1)
print min(timeit.Timer('print pylist1').repeat(7,1000))

这只会与NameError: global name 'pylist1' does not exist崩溃。这很奇怪,因为print pylist1工作得很好!?在做我想做的事情时需要帮助。你知道吗


Tags: 内存importredis列表servermy基准语句
1条回答
网友
1楼 · 发布于 2024-09-29 19:30:29

Timer的文档说明:

Class for timing execution speed of small code snippets.

The constructor takes a statement to be timed, an additional statement used for setup, and a timer function. Both statements default to 'pass'; the timer function is platform-dependent (see module doc string). If 'globals' is specified, the code will be executed within that namespace (as opposed to inside timeit's namespace).

[...]

这告诉您,Timer执行的语句在默认情况下是在它自己的名称空间中执行的,该名称空间既不能访问外部名称空间,也不能修改它们。要更改此设置,可以使用setup语句导入所需的名称:

Timer(..., setup='from __main__ import pylist1')

或者只指定使用当前命名空间来执行代码:

Timer(..., globals=globals())

请注意,如果您正在计时的语句修改了变量,它们实际上会在模块中更改。 最好使用globals的副本:

Timer(...., globals=globals().copy())

# even better

import copy
Timer(..., globals={'pylist1': copy.deepcopy(pylist1))

在这种情况下,所分析的代码不会修改全局变量

相关问题 更多 >

    热门问题