cProfile Example and iPython Magic Shortcut %prun

Running cProfile is a bit of a pain.

You have to pass your function and all its scope as a string to cProfile, which is.. just a pain.

cProfile.run('''
def test(n):
    x = 1
    for i in range(n):
        x = x * 2
''')

iPython has a magic function that lets you use the current scope.

def test(n):
    x = 1
    for i in range(n):
        x = x * 2
 %prun test(100000)

         4 function calls in 0.753 CPU seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.752    0.752    0.753    0.753 :1(test)
        1    0.002    0.002    0.002    0.002 {range}
        1    0.000    0.000    0.753    0.753 :1()
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s