そこで、timeitモジュールを使用して変数の代入の速度を調べていたところ、非常に興味深い結果がいくつか見つかりました。複数行の割り当ては、一般的に単一行の割り当てよりも高速であることがわかりました。どうしてこれなの?
time.sleep(1)
また、下のループに入れると、速度の結果に大きな影響を与えるように見えることも注目に値します。どうしてこれなの?
以下の私のコードと結果:
時間なし。睡眠:
dis results for myfunc1:
5 0 LOAD_CONST 2 ((10, 10))
3 UNPACK_SEQUENCE 2
6 STORE_FAST 0 (x)
9 STORE_FAST 1 (y)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
dis results for myfunc2:
7 0 LOAD_CONST 1 (10)
3 STORE_FAST 0 (x)
8 6 LOAD_CONST 1 (10)
9 STORE_FAST 1 (y)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
Speed results for single line assignment:
4.61830006532e-06
4.10515561362e-06
4.10515561362e-06
4.61830006532e-06
4.61830006532e-06
4.10515561362e-06
4.10515561362e-06
4.10515561362e-06
4.10515561362e-06
4.10515561362e-06
4.10515561362e-06
Speed Results for multi-line assignment:
4.10515561362e-06
3.59201116192e-06
4.10515561362e-06
3.59201116192e-06
4.10515561362e-06
3.59201116192e-06
3.59201116192e-06
4.10515561362e-06
4.10515561362e-06
3.59201116192e-06
4.10515561362e-06
time.sleepで:
dis results for myfunc1:
5 0 LOAD_CONST 2 ((10, 10))
3 UNPACK_SEQUENCE 2
6 STORE_FAST 0 (x)
9 STORE_FAST 1 (y)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
dis results for myfunc2:
7 0 LOAD_CONST 1 (10)
3 STORE_FAST 0 (x)
8 6 LOAD_CONST 1 (10)
9 STORE_FAST 1 (y)
12 LOAD_CONST 0 (None)
15 RETURN_VALUE
Speed results for single line assignment:
4.61830006532e-06
5.13144451708e-06
9.03134234993e-05
0.000157022202221
8.77477012411e-05
4.61830006504e-06
4.7722434009e-05
1.59074780033e-05
0.000105707757051
0.000324307293475
1.43680446492e-05
Speed Results for multi-line assignment:
1.33417557446e-05
0.000202692058421
1.33417557446e-05
0.000163693080093
1.3854900196e-05
1.3854900196e-05
0.000279663726175
0.000142141013121
0.000202692058423
0.000200639480614
0.000103655179245
コード:
import dis,timeit,time
#define the different methods of assignment
def myfunc1():
x,y=10,10
def myfunc2():
x=10
y=10
#used simply for viewing how they are assigned
print "dis results for myfunc1:"
dis.dis(myfunc1)
print "dis results for myfunc2:"
dis.dis(myfunc2)
print "\n"
print "Speed results for single line assignment:"
#repeat 10 times, with looping 100 times per repeat to show speed and consistency
for x in range(11):
print timeit.timeit(stmt="x,y=10,10",number=100)
#time.sleep(1)
print "\n"
print "Speed Results for multi-line assignment:"
#repeat with the same method for previous test
for x in range(11):
print timeit.timeit(stmt="x=10;y=10;",number=100)
#time.sleep(1)
ベンチマーク:Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32