This post will help you to use line_profiler for python (2.5.x) as well as python3 (python 3.x) line_profiler will help you to profile the time taken to execute each individual lines of code. The profiler is implemented in C via Cython, an optimizing static compiler for Python programming language as well as Cython programming language (based on Pyrex).
1. Install mercurial (Skip this step if using Official line_profiler from rkern)
sudo apt-get install mercurial
Note: rkern’s Official line_profiler has recently added Python3 support in 1.0 release
2. Clone the line_profiler repository
git clone https://github.com/rkern/line_profiler.git
You can directly jump to Step 3 now, as Python3 support is provided by rkern’s line_profiler 🙂
Note: If this doesn’t work for you properly (Seems that they have kept support for 3.x on hold for now). You can clone this repository which is a fork of the above with 3.x compatibility.
hg clone https://bitbucket.org/kmike/line_profiler
or you can clone this one too:
hg clone https://bitbucket.org/thefalcon/line_profiler
3. Navigate into the line_profiler clone folder
4. Now you need to Install Cython (for python) / Cython3 (for python 3.x)
sudo apt-get install cython sudo apt-get install cython3
5. Install line_profiler by running:
python setup.py install
b) line_profiler for python3
python3 setup.py install
6. Go to the folder where your .py file is located and run the following command:
kernprof.py -l example.py; python3 -m line_profiler example.py.lprof
“kernprof.py -l example.py” will create an instance of LineProfiler and it will be inserted in __builtins__ namespace with the name ‘profile’. It is written to be used as a decorator. Therefore you can decorate any function you want to profile using @profile Here’s an example:
@profile def add(a,b): ....
The default behavior of kernprof is to compile the .py into a binary file like ‘example.py.lprof’. To display the result you need to immediately run the command “python3 -m line_profiler example.py.lprof” (for python3) or “python -m line_profiler example.py.lprof” (for python) for displaying the formatted results. Reference: 1. http://pythonhosted.org/line_profiler/
Let the Windows be open, and feel the Freedom.