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 Comment