How to make Python programs run faster

Source: Internet
Author: User

Principle 1: Not optimized

Principle 2: Do not optimize those unimportant parts (otherwise it will decrease readability)

Solution:

1. Using functions, local variables are much faster than global variables. Use functions as much as possible, such as main ()

2. Selective removal of property access. If you use the From math import sqrt instead of calling math.sqrt () more than once in the program, or declaring the local variable directly.

Import Math def compute_roots (nums):     = math.sqrt    = []    = res.append    for in  nums:        res_append (sqrt (n))     return Res

# Micro-Optimization
A = {i:i**2 for I in range (1000)} # Faster
b = [Dict (i=i**2) for I in range (1000)] # slower

3. Avoid unnecessary abstractions, such as adorners, @property, etc.

4. Use built-in strings, tuples, lists, collections, dictionaries and other containers.

5. Avoid unnecessary data structures or copy actions

6. Use CPython or PyPy and so on.

Ps: >> optimization before the first to run up, first to have the correct algorithm! Algorithms with low complexity are far more important than program optimization.

How to make Python programs run faster

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.