6 Python performance Optimization tips

Source: Internet
Author: User
Tags for in range

Original: 6 Python performance Tips

6 Python performance Optimization tips

Translator: Dwqs

Python is a very cool language, because very few Python code can do a lot of things in a short time, and Python can easily support multitasking and multiprocessing.

Python's critics claim that Python performance is inefficient and slow to perform, but it is not: try the following 6 tips to speed up your Pytho application.

1, the key code can depend on the expansion package

Python makes many programming tasks simple, but does not always provide the best performance for mission-critical tasks. Using C, C + +, or machine language expansion packs to perform critical tasks can greatly improve performance. These packages are platform-dependent, that is, you must use a specific package that is relevant to the platform you are using. In short, the solution provides portability for some applications in exchange for performance, which you can obtain only by programming directly to the underlying host. Here are some extensions you can consider adding to your personal extension library:

    • Cython
    • Pyinlne
    • PyPy
    • Pyrex

These packages have different roles and methods of execution. For example, Pyrex allows Python to handle some memory tasks easily and efficiently; Pyinline can directly let you use C code in Python applications, although inline code is compiled separately, but if you can use C code efficiently, it can handle everything in one place.

2. Use keyword sorting

There are many old Python code that will take extra time to create a custom sort function when executed. The best way to sort is to use the keyword and the default sort () method to see the following example:

operatorsomelist = [(1, 5, 8), (6, 2, 4), (9, 7, 5)]somelist.sort (key=operator. Itemgetter (0)) somelist# Output = [(1, 5, 8), (6, 2, 4), (9, 7, 5)]somelist.sort (key=operator. Itemgetter (1)) Somelist#output = [(6, 2, 4), (1, 5, 8), (9, 7, 5)]somelist.sort (key=operator. Itemgetter (2)) Somelist#output = [(6, 2, 4), (9, 7, 5), (1, 5, 8)] ,

The list of each case is sorted according to the index you choose as the keyword parameter, which is also true for string and numeric sorting.

3. Optimized circulation

Each programming language emphasizes the optimization of loop statements, and Python is the same. While you can rely on rich technology to make loops run faster, one way developers often overlook it is to avoid using dots to stitch strings inside loops. For the following example:

Lowerlist = ['this ' is'lowercase']upper = str.upperupperlist = []append = Upperlist.append  for  in Lowerlist:    append (upper (word))    print (upperlist)    #Output = [' this ' is ' ' lowercase ']

Every call to Str.upper,python will find the value of this method. But if you put the results of the evaluation into a variable, you can improve the performance of the program. The key is to reduce the number of cycles executed in Python, because Python resolves these instances to be slow.

4. Use the new version

Anyone searching for Python data online will find countless information about the Python version migration. Typically, each version of Python is optimized and improved for the previous version to make Python run faster. The limiting factor is whether the library you like is also improving for Python's new version.

When you use a new library and get a new version of Python, you need to make sure the code is still running, checking the app, and correcting the differences.

Then, if you just guarantee that the app will run on the new version, you may miss the update for the new feature. Once you have made improvements, configure the application under the new version, check the problem area and prioritize the new feature updates, and for the previous upgrade, users will see a greater performance boost.

5. Try a variety of programming methods

Every time you create an application, you use the same programming method, and in some cases, the program will run slower than expected. Do some small experiments in the process of analysis. For example, when you manage data items in a dictionary, you can use a secure method to determine whether a data item already exists and need to update it, or you can add an entry directly and then handle a situation where the item does not exist at all.

n = 16myDict = {} for in range (0, N):    char' ABCD '[i%4]    ifChar   in mydict:        mydict[char] = 0        mydict[char] + = 1        print (mydict)

When Mydict is empty, the above code will usually run faster. But when Mydict already has data to fill, there is a better way to choose:

n = 16myDict = {} for in range (0, N):    char' ABCD '[i%4]    try:        mydict[char] + = 1    except Keyerror:        mydict[char] = 1    print (mydict)

Output in both cases, the {‘d‘: 4, ‘c‘: 4, ‘b‘: 4, ‘a‘: 4} only difference is how the output is obtained. Standing outside the box thinking about and creating new programming skills can get your program running faster.

6. Cross-Compiling program

Developers sometimes forget that the computer does not recognize any of the current application languages, it only recognizes machine code. In order to run the program, an application is required to convert human-readable code into code that can be recognized by the computer. When you write a program in one language, such as Python, and then run it in a different language, such as C + +, it makes sense from a performance standpoint. This depends on what you want to do with the app and what resources the host system can provide.

An interesting cross compiler, Nuitka, can convert Python to C + + code, as a result you can execute the application in native mode instead of relying on the interpreter. Depending on the platform and the task, you can see significant performance improvements.


Original text: http://www.ido321.com/1433.html

6 Python performance Optimization tips

Related Article

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.