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__ + ' () ' ; |