2016-10-23 2 views
0

私はpython2.7で2つの比較可能なステートメントをベンチマークしようとしています。Python timeit関数がNameErrorでクラッシュする:グローバル名が存在しません

メモリから取得した数字のリストを1つのステートメントで出力します。もう1つのステートメントは、同じサーバー上に管理されているredisリストから取得した同じ番号のリストを出力します。

など。私はベンチマークprint pylist1print pylist2にはtimeitを使用するにはどうすればよい

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

私はPythonシェルで次のようにしようとしている:

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が完璧に機能するので、それは変です!私が正しくやろうとしていることをするのに助けが必要です。 Timerため

答えて

2

ドキュメントは言う:

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によって実行されたステートメントは、デフォルトでは、外側の名前空間へのアクセスを持っても、それはそれを修正しない独自の名前空間内で実行されることを示しています。

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

それともコードを実行するために、現在のネームスペースを使用するように指定します。:このあなたが必要と名をインポートするために、セットアップ文を使用することができます変更するには

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

注文の場合は、あることタイミングは、モジュール内で実際に変更される変数を変更します。 その代わりglobalsのコピーを使用する方が良い場合があります。あなたのグローバル変数を変更することはありませんプロファイルされている。このコードでは

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

# even better 

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

関連する問題