Aufwind
Aufwind

Reputation: 26288

Are there tools, for analyzing python code?

I am looking for a tool to analyze my python script. For example

  1. which part of the code takes the most time
  2. which part of the code consumes too much memory
  3. and so on...

Is there something like that?

Upvotes: 2

Views: 265

Answers (3)

Adri G.
Adri G.

Reputation: 1

I frequently use Ipython to profile my code. Executing a script with the magic command "%run" like this (inside an ipython prompt):

    %run -p your_python_script.py

runs the program under the control of the Python profiler module.

You can even profile statements (e.g. a function call) with the "%prun" magic:

    %prun a_python_statement

What is nice about %prun, is that it executes the statement in the context of your current session (i.e. you can use variables you previously defined and anything else in your current namespace).

If you want to get per-line profiling information, I found the line_profiler module to be quite handy. It is a bit old, but it does the job... as expected from something coded by Robert Kern ;-).

Upvotes: 0

senderle
senderle

Reputation: 151187

Take a look at cProfile. Here's a usage example:

me@mine:~ $ cat foo.py 
def double(i):
    return i * 2

def halve(i):
    return i / 2.0

for i in range(10000):
    double(i)
    halve(i)
me@mine:~ $ python -m cProfile foo.py 
         20005 function calls in 0.009 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.009    0.009 <string>:1(<module>)
        1    0.006    0.006    0.009    0.009 foo.py:1(<module>)
    10000    0.001    0.000    0.001    0.000 foo.py:1(double)
    10000    0.002    0.000    0.002    0.000 foo.py:4(halve)
        1    0.000    0.000    0.009    0.009 {execfile}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {range}

A good memory profiler, as mentioned in the post linked to by Sven Marnach, is Heapy

Upvotes: 3

Sven Marnach
Sven Marnach

Reputation: 602735

  1. Python has a built-in profiler

  2. There are various memory profilers for Python

Upvotes: 5

Related Questions