Python Performance Optimization__python

Source: Internet
Author: User
Python Performance Optimization

Performance Optimization–making A program run Faster–is closely related to refactoring. Refactoring makes existing source code more readable and less complex on the inside without it changing on the O Utside. Refactoring is a costly operation. Typically, a 80/20 rule applies. A 20% effort is needed to implement the bulk of the program. Then another 80% effort (and budget) is needed to optimize, refactor, extend and/or document the program.

Do not worry about performance during development. You are the produce correct results (with correct input) before your know what is making it slow.

Not all parts of the source code would be optimizable. In Python, many operations such as dictionary lookups and regular expressions as are as efficient can. Some operations in your code simply need to happen to make the program work. In this case, micro-optimizations (e.g., making a function 1% faster) are a waste of time.

Profiling

Typically, the top 20% slow parts of the "program may" benefit from optimization. To find the slow parts your need to profile the source code. The profile () function below uses Python's CProfile module to return a string of performance statistics. To use it can simply copy it int0 a test script:

def profile (function, *args, **kwargs):      "" Returns Performanc E statistics (as a string) for the given function.      ""      def _run ():          function (*args, **kwargs)      import cProfile as profile      import Pstats & nbsp;    import OS      import sys; sys.modules[' __main__ '].__profile_run__ = _run      id = function.__name__ + ' () '     ; 

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.