Modules

Modules#

Here we import our own module called myprofile (we have it in the same directory as this notebook)

import myprofile

We have a docstring at the top – the comments there are what appear when we ask for help

help(myprofile)
Help on module myprofile:

NAME
    myprofile

DESCRIPTION
    A very simple profiling class.  Define some timers and methods
    to start and stop them.  Nesting of timers is tracked so we can
    pretty print the profiling information.
    
    # define a timer object, labeled 'my timer'
    a = timer('my timer')
    
    This will add 'my timer' to the list of keys in the 'my timer'
    dictionary.  Subsequent calls to the timer class constructor
    will have no effect.
    
    # start timing the 'my timer' block of code
    a.begin()
    
    ... do stuff here ...
    
    # end the timing of the 'my timer' block of code
    a.end()
    
    for best results, the block of code timed should be large
    enough to offset the overhead of the timer class method
    calls.
    
    Multiple timers can be instantiated and nested.  The stackCount
    global parameter keeps count of the level of nesting, and the
    timerNesting data structure stores the nesting level for each
    defined timer.
    
    timeReport() is called at the end to print out a summary of the
    timing.
    
    At present, no enforcement is done to ensure proper nesting.

CLASSES
    builtins.object
        Timer
    
    class Timer(builtins.object)
     |  Timer(name)
     |  
     |  Methods defined here:
     |  
     |  __init__(self, name)
     |      Initialize self.  See help(type(self)) for accurate signature.
     |  
     |  begin(self)
     |  
     |  end(self)
     |  
     |  ----------------------------------------------------------------------
     |  Data descriptors defined here:
     |  
     |  __dict__
     |      dictionary for instance variables
     |  
     |  __weakref__
     |      list of weak references to the object

FUNCTIONS
    time_report()

DATA
    stack_count = 0
    timer_nesting = {}
    timer_order = []
    timers = {}

FILE
    /home/runner/work/reu-python-tutorial/reu-python-tutorial/content/02-python-functions-classes/myprofile.py

This module simply provides a way to time routines (python and ipython have built-in methods for this too)

t = myprofile.Timer("main loop")
t.begin()

sum = 0.0
for n in range(1000):
    sum += n**2


t.end()
myprofile.time_report()

print(sum)
main loop:  0.0001709461212158203
332833500.0

In the file myprofile.py, you will see a block of code under

if __name__ == "__main__":

That code is executed if the file is run directly, either from the commandline as:

python myprofile.py

for through the %run magic

%run myprofile
1:  10.000101089477539
2:  25.000246286392212
   3:  20.000116109848022