Code optimization is one of the obstacles that every developer now a days come across. There are lot of tools present now a days to optimize code. You can find python builtin or 3rd party modules for code optimization. Below I have mentioned a few codes optimization tools that I have used.
Builtin Modules
Profile
How To : First of all import profile into you python code. Then at the main method use the profile.run() method. On executing the py file we will provide the profiler output. An example code is shown below:
Profile module also provides runtx( ) for custom profiler generation.import profile
def add(first, second): return first + second
profile.run(' print add(1,2); print ')
cProfile
How To :This module can be used in two ways. One is to import the module and call it as cProfile.run( <your method> )Second is to call the cProfile module at the time of file execution.
python -m cProfile pythonfile.py
pstat
How To: Standard report produced by the profile module is not very flexible. So depending upon the need the user can save the output of the run() or runtx() and process it using the Stats class from pstat.
Third Party Modules
Line Profiler
How To : First of all install line profile using the following command.
Then add the @profile above your method definition. Finally execute the code using the following command.pip install line_profiler
$ kernprof.py -l -v fib.py
No comments:
Post a Comment