Python Variable Exchange performance optimization

Source: Internet
Author: User

New in many ways Python performance optimizations see the value of swapping two variables can be used

A, B = b,a
This can improve performance

>>> 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>>>

From the running time, it really saved half the time.

Get Python bytecode with dis

>>> def func (): ...     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)             store_fast               0 (b)             load_const               0 (None)             RETURN _value>>>

It can be seen that the main rot_two instruction is the credit:

Consult a Python document for instructions such as Rot_two Rot_three Rot_four, which can be exchanged directly for two variables, three variables, and four variable values

Read the ceval.c file in the source code of python3.4 to see:

       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 ();        }
Is that the specific C language of these instructions implements the
After all, the speed is fast or because A, B = B,a is all using the pointer operation

Python Variable Exchange performance optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.