Profiling

From IronPython Cookbook

milestone

At the top of app.py place "import milestone". Then anywhere in your code, regardless of thread or module, call

milestone('reached point x')

You can also add string formatting arguments:

milestone('reached point %s', 'y')

All references to milestone can easily be commented out or removed with a single find and replace.

When you're done do:

import milestone
milestone.report()

Which will print a very rudimentary chronological report for each milestone reached:

(thread#, milestone, time reached)

You can disable the milestones by setting ENABLE = False.

milestone.py

ENABLE = True

if ENABLE:
    from System.Threading import Thread
    
    from datetime import datetime
    import threading
    
    _tls = threading.local()
    
    class Stopwatch(object):
        def __init__(self):
            self.start = datetime.now() 
        
        def Mark(self):
            self.stop = datetime.now()
        
        def GetElapsed(self):
            td = self.stop - self.start
            return td.seconds + 1e-6 * td.microseconds
        
        def Clone(self):
            s = Stopwatch()
            s.start = self.start
            return s
        
        Elapsed = property(GetElapsed)
        
    _sw = Stopwatch()
    
    def set(name, *args):
        if hasattr(_tls, 'sw'):
            sw = _tls.sw
        else:
            sw = _tls.sw = _sw.Clone()
           
        sw.Mark()
        if args:
            name %= args
        records.append((Thread.CurrentThread.ManagedThreadId, name, sw.Elapsed))
 
    __builtins__['milestone'] = set        
else:
    def _pass(*args):
        pass
    
    __builtins__['milestone'] = _pass
    
records = []
def report():
    for r in records:
        print r           

I know it sucks to use datetime for precision timing, but I beleive that it is no less precise than any of the timing methods available in silverlight. Oh for a real profiler...


Back to Contents.

TOOLBOX
LANGUAGES