Gprof2dot

2009/12/06

Profiling

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.

Gprof2Dot

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.

As you can see for example here .
You also need to have graphviz to be able to actually generate the final graph.

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).


elisp fun

2009/12/02

Problem

As we all know programmers are lazy, repetition is the evil, we want to type as fast as possible.
Using C-like languages you always need to put the comma in the end.

Normally after the comma you also want to go to newline and indent, so why not put together those two things and automate it?

If you also like yasnippet then you’ll find this feature even nicer.
I took from this feature textmate , a wonderful text editor which comes with this setting by default.
As we’ll see we don’t need many lines of elisp code to end up with a much more powerful and flexible version of this nice feature.

Solution

newline-force

We first define a first function newline-force
Here it is:

(defun newline-force()
  "Goes to newline leaving untouched the rest of the line"
  (interactive)
  (progn
    (end-of-line)
    (newline-and-indent)))

This function goes to end of line and calls the predefined function newline-and-indent, which goes to newline and indent according to mode
In more detail:

  • interactive: function is available for user
  • progn: executes a sequence of disjointed operations

Read the rest of this entry »


Follow

Get every new post delivered to your Inbox.