Skip to content

Instantly share code, notes, and snippets.

@danriti
Last active February 26, 2022 07:20
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save danriti/8015889 to your computer and use it in GitHub Desktop.
Save danriti/8015889 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()
@shz224
Copy link

shz224 commented Jun 10, 2020

Thanks for offering such a convenient tool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment