Six tips to help you improve Python performance

Source: Internet
Author: User
Tags lowercase pack readable sort versions in python

This article introduces six tips to help you improve Python's efficiency, this article explains key code using external feature packs, using keys for sorting, optimizing loops, using newer Python versions, and more, and friends can refer to

People who don't like python often vomit. Python is too slow to run. But that is not the case. Try the following six tips to speed up your Python application.

Tip One: Key code uses external feature packs

Python simplifies many programming tasks, but it often behaves poorly on time-sensitive tasks. The use of the external function pack of C + + or machine language to handle time sensitive tasks can effectively improve the operational efficiency of the application. These feature packs are often attached to a particular platform, so you have to choose the right Feature pack based on the platform you're using. In short, the trick is to sacrifice the portability of the application in exchange for the operational efficiencies that can be achieved only through direct programming to the underlying host. Here are some of the feature packs you can choose to use to improve your productivity:

Cython

Pylnlne

PyPy

Pyrex

The usefulness of these feature packs is different. For example, using the C language data type enables tasks that involve memory operations to be more efficient or intuitive. Pyrex can help Python to extend this feature. Pylnline allows you to use C code directly in Python applications. Inline code is compiled independently, but it keeps all the compiled files somewhere, and can take full advantage of the high efficiency provided by C language.

Tip Two: Use keys when sorting

Python contains a number of ancient collations that can take a lot of time to create custom sorting methods, and these sorts of sorting methods can delay the actual speed of the program. The best way to sort it is to use as many keys as possible and the built-in sort () method. For example, take the following code:

The code is as follows:

Import operator

Somelist = [(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)],

In each case, the list is sorted according to the index you choose to use as a key parameter. This method is useful not only for numeric types, but also for string types.

Tip Three: For the optimization of the cycle

Each programming language emphasizes the optimal loop scheme. When using Python, you can use a lot of tricks to get the loop running faster. However, one trick that developers often forget is to try to avoid accessing the properties of variables in a loop. For example, take the following code:

The code is as follows:

Lowerlist = [' This ', ' is ', ' lowercase ']

Upper = Str.upper

Upperlist = []

Append = Upperlist.append

For word in lowerlist:

Append (upper (word))

Print (upperlist)

#Output = [' This ', ' is ', ' lowercase ']

Every time you call Str.upper, Python calculates the value of the equation. However, if you assign the value to a variable, the result of the evaluation can be known in advance, and the Python program will run faster. So the key is to minimize Python's effort in the loop. Because Python interprets the characteristics of execution, it slows down its speed considerably in the example above.

(Note: There are a lot of ways to optimize loops, and this is just one of them.) For example, many programmers would argue that list derivation is the best way to increase the speed of a cycle. The key is that optimizing the loop is a good choice to improve the speed of your application. )

Tip Four: Use the newer Python version

If you search for Python online, you'll find that countless messages are about how to upgrade the Python version. Typically, each version of Python contains the optimized content to run faster than the previous version. However, the limiting factor is whether your favorite library has synchronized updates to support the new Python version. Rather than arguing that the function library should be updated, the key is whether the new Python version is efficient enough to support this update.

You have to make sure your code is still running in the new version. You need to use a new library to experience the new Python version, and then you need to check your application when making critical changes. Only when you have completed the necessary corrections can you realize the difference in the new version.

However, if you are just making sure that your application runs in the new version, you are likely to miss the new features provided by the new version. Once you have decided to update, please analyze your application's performance under the new version and check for possible problems, and then prioritize the new versions of the features for those parts. Only in this way can users be aware of the improved application performance at the beginning of the update.

Tip Five: Try multiple coding methods

Using the same encoding method every time you create an application almost invariably causes the application to run inefficiently. You can try some experimental methods in the process analysis. For example, when dealing with data items in a dictionary, you can use a secure method to make sure that the data item already exists and then update it, or you can update the data item directly to separate the nonexistent data items as special cases. Take a look at the first piece of code below:

The code is as follows:

n = 16

Mydict = {}

For I in range (0, N):

char = ' ABCD ' [i%4]

If char not in mydict:

Mydict[char] = 0

Mydict[char] + + 1

Print (mydict)

This code runs faster when the initial mydict is empty. Typically, however, mydict fills up the data and fills in at least a large portion of the data, which is more efficient in another way.

The code is as follows:

n = 16

Mydict = {}

For I in range (0, N):

char = ' ABCD ' [i%4]

Try

Mydict[char] + + 1

Except Keyerror:

Mydict[char] = 1

Print (mydict)

The output results are the same in both methods. The difference is how the output is obtained. Jump out of the normal mindset and create new programming skills that will make your application more efficient.

Tip Six: Cross-compile your application

Developers sometimes forget that computers don't really understand the programming language used to create modern applications. The computer understands the machine language. In order to run your application, you use an application to convert the human-readable code you have compiled into machine-readable code. Sometimes you write applications in a language such as Python, and then run your application in a language such as C + +, which is feasible in terms of running. The key is what you want your application to accomplish, and what resources your host system can provide.

Nuitka is an interesting crossover compiler that converts your Python code into C + + code. In this way, you can perform your own application in native mode without having to rely on the interpreter program. You will find that your application has improved significantly, but this will vary depending on the platform and the task.

(Note: Nuitka is still in the testing phase, so please pay more attention to it in practical applications.) In fact, the best thing to do now is to experiment with it. In addition, there is room for discussion as to whether cross compilation is the best way to improve operational efficiency. Developers have been using cross compilation for years to increase the speed of applications. Remember, each solution has its pros and cons, and weigh it carefully before you use it in a production environment. )

When using a cross compiler, make sure that it supports the Python version you are using. Nuitka supports Python2.6, 2.7, 3.2 and 3.3. In order for the solution to take effect, you need a Python interpreter and a C + + compiler. Nuitka supports many C + + compilers, including Microsoft Visual Studio, MinGW, and CLANG/LLVM.

Cross-compilation can cause some serious problems. For example, when using Nuitka, you'll find that even a small program consumes a lot of drive space. Because Nuitka uses a series of dynamic link libraries (DDLs) to perform Python functions. So if you're using a system with a very limited resource, this might not be a viable option.

Conclusion

The six tips outlined above can help you create a more efficient Python application. But there is no silver bullet. These tips do not necessarily work every time. In a particular Python version, some of the tricks may be better than others, but this sometimes depends on the platform's differences. You need to summarize and analyze your application, find its inefficiencies, and then try these tips to find the best way to solve the problem.

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.