Skip to content

Instantly share code, notes, and snippets.

@alex-bender
Forked from danriti/README.md
Created November 22, 2017 15:54
Show Gist options
  • Save alex-bender/2256288c47b520017f1f190df9005b8c to your computer and use it in GitHub Desktop.
Save alex-bender/2256288c47b520017f1f190df9005b8c to your computer and use it in GitHub Desktop.
Line Profiling in Python

Install the line_profiler module:

[driti@ubuntu ]$ pip install line_profiler

Add the @profile decorator and run:

[driti@ubuntu ]$ kernprof.py -l -v example.py
None
Wrote profile results to example.py.lprof
Timer unit: 1e-06 s

File: example.py
Function: so_slow at line 5
Total time: 5.00598 s

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     5                                           @profile
     6                                           def so_slow(bar):
     7                                               """ Simulate a slow function. """
     8         1      5005974 5005974.0    100.0      sleep(5)
     9         1            3      3.0      0.0      return bar

File: example.py
Function: its_time_for_the_calculator at line 11
Total time: 5.22016 s

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    11                                           @profile
    12                                           def its_time_for_the_calculator(foo):
    13                                               """ It's time for the calculator. """
    14         1            3      3.0      0.0      if not isinstance(foo, int):
    15                                                   return None
    16
    17         1            0      0.0      0.0      a = []
    18    100001        48222      0.5      0.9      for i in xrange(foo):
    19    100000        62404      0.6      1.2          a.append(i)
    20
    21         1      5006008 5006008.0     95.9      b = so_slow(a)
    22
    23         1            1      1.0      0.0      c = 0
    24    100001        48883      0.5      0.9      for i in xrange(foo):
    25    100000        54635      0.5      1.0          c += i
    26
    27         1            0      0.0      0.0      return None
#!/usr/bin/python
from time import sleep
@profile
def so_slow(bar):
""" Simulate a slow function. """
sleep(5)
return bar
@profile
def its_time_for_the_calculator(foo):
""" It's time for the calculator. """
if not isinstance(foo, int):
return None
a = []
for i in xrange(foo):
a.append(i)
b = so_slow(a)
c = 0
for i in xrange(foo):
c += i
return None
def main():
print its_time_for_the_calculator(100000)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment