从多方面新讲python性能优化看到交换两个变量的值可以使用
a,b = b,a这样可以提高性能
>>> from timeit import Timer >>> Timer("t=a;a=b;b=t","a=1;b=2").timeit() 0.06279781319366587 >>> Timer("a,b=b,a","a=1;b=2").timeit() 0.0378979925538232 >>>
通过dis得到python字节码
>>> def func(): ... a,b = b,a ... >>> import dis >>> dis.dis(func) 2 0 LOAD_FAST 0 (b) 3 LOAD_FAST 1 (a) 6 ROT_TWO 7 STORE_FAST 1 (a) 10 STORE_FAST 0 (b) 13 LOAD_CONST 0 (None) 16 RETURN_VALUE >>>
查阅python文档可以知道有ROT_TWO ROT_THREE ROT_FOUR这样的指令,可以直接交换两个变量、三个变量、四个变量的值
在python3.4的源码中查阅ceval.c文件可以看到:
TARGET(ROT_TWO) { PyObject *top = TOP(); PyObject *second = SECOND(); SET_TOP(second); SET_SECOND(top); FAST_DISPATCH(); } TARGET(ROT_THREE) { PyObject *top = TOP(); PyObject *second = SECOND(); PyObject *third = THIRD(); SET_TOP(second); SET_SECOND(third); SET_THIRD(top); FAST_DISPATCH(); }就是这些指令的具体C语言实现了
原文地址:http://blog.csdn.net/wlyfls/article/details/39989523