I want to share with you a nice trick which, even if not fundamental, is still very useful.
You can also use this to impress your girlfriend.
Sometimes profiling is necessary to understand which part of our code are taking so long.
Python offer different alternatives, I advice you to read the official python documentation to get an idea.
Another very nice thing is gprof2dot .
This little program takes into input profiling data in many different formats and converts it to a dot file, keeping all the valuable informations.
Scripting and emacs integration
Given that I want to automate it and I want to use it also from emacs I wrote a simple bash script:
#!/bin/bash FNAME=$1 if [ ! -f $FNAME ] then echo "file $FNAME not found, executing from $PWD" exit 1 fi # discard filename shift # change those variables as you prefer STATS="output.pstats" TYPE=png OUT=output.$TYPE OPEN="open" # $@ collect all the arguments for the python script # it doens't contain the file name after the shift python -m cProfile -o $STATS $FNAME $@ gprof2dot.py -f pstats $STATS | dot -T$TYPE -o $OUT rm $STATS $OPEN $OUT
You can find this script also in my emacs configuration .
Now we’re almost done, just put this somewhere in the emacs exec-path and you’re ready to use it!
Just press Meta-! on a python buffer and launch “gprofile.sh python_file.py [extra args..]”
To automate even more this little elisp functions does that for you:
(defun gprof () (interactive) (shell-command (concat "gprofile.sh " buffer-file-name)))
But at the moment it doesn’t take arguments for the script (will fix it soon).