所以我正在使用timeit模块查看变量赋值的速度,我发现了一些非常有趣的结果。我发现多行分配通常比单行分配更快。这是为什么?
另外,值得注意的是,当将time.sleep(1)
置于下面的循环中时,它似乎会影响速度结果 显着 。这是为什么?
我的代码和结果如下:
没有 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
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
答案 0 :(得分:0)
我发现多行分配通常比单行分配更快。这是为什么?
因为UNPACK_SEQUENCE
比LOAD_CONST
慢。
另外,值得注意的是,当将time.sleep(1)放在下面的循环中时,它似乎会显着影响速度结果。这是为什么?
因为100次迭代对于快速操作而言太低,并且受(低)时钟精度的影响很大。使用number=10000000
重新测试,无论睡眠如何,您都会得到大致相同的结果。