profile#

profile(run, follow=None, print_stats=True, *args, **kwargs)[source]#

Profile the line-by-line time required by a function.

Interface to the line_profiler library.

Note: sc.profile() shows the time taken by each line of code, in the order the code appears in. sc.cprofile() shows the time taken by each function, regardless of where in the code it appears.

Parameters:
  • run (function) – The function to be run

  • follow (function) – The function or list of functions to be followed in the profiler; if None, defaults to the run function

  • print_stats (bool) – whether to print the statistics of the profile to stdout

  • args – Passed to the function to be run

  • kwargs – Passed to the function to be run

Returns:

LineProfiler (by default, the profile output is also printed to stdout)

Example:

def slow_fn():
    n = 10000
    int_list = []
    int_dict = {}
    for i in range(n):
        int_list.append(i)
        int_dict[i] = i
    return

class Foo:
    def __init__(self):
        self.a = 0

    def outer(self):
        for i in range(100):
            self.inner()

    def inner(self):
        for i in range(1000):
            self.a += 1

foo = Foo()
sc.profile(run=foo.outer, follow=[foo.outer, foo.inner])
sc.profile(slow_fn)

# Profile the constructor for Foo
f = lambda: Foo()
sc.profile(run=f, follow=[foo.__init__])