viff

changeset 987:909c5df8e5a1

New decorator for profiling.
author Martin Geisler <mg@daimi.au.dk>
date Wed, 01 Oct 2008 11:02:26 +0200
parents 6899c91c1372
children 6612f982d5e2
files viff/util.py
diffstat 1 files changed, 30 insertions(+), 0 deletions(-) [+]
line diff
     1.1 --- a/viff/util.py	Tue Sep 23 11:33:35 2008 +0200
     1.2 +++ b/viff/util.py	Wed Oct 01 11:02:26 2008 +0200
     1.3 @@ -25,6 +25,7 @@
     1.4  __docformat__ = "restructuredtext"
     1.5  
     1.6  import os
     1.7 +import time
     1.8  import random
     1.9  import warnings
    1.10  from twisted.internet.defer import Deferred, succeed, gatherResults
    1.11 @@ -249,6 +250,35 @@
    1.12      return long(p)
    1.13  
    1.14  
    1.15 +PHASES = {}
    1.16 +
    1.17 +def begin(result, phase):
    1.18 +    PHASES[phase] = time.time()
    1.19 +    return result
    1.20 +
    1.21 +def end(result, phase):
    1.22 +    stop = time.time()
    1.23 +    start = PHASES.pop(phase, stop)
    1.24 +    print "%s from %f to %f (%f sec)" % (phase, start, stop, stop - start)
    1.25 +    return result
    1.26 +
    1.27 +def profile(method):
    1.28 +    if not os.environ.get('VIFF_PROFILE'):
    1.29 +        return method
    1.30 +
    1.31 +    @wrapper(method)
    1.32 +    def profile_wrapper(self, *args, **kwargs):
    1.33 +        label = "%s-%s" % (method.__name__, self.program_counter)
    1.34 +        begin(None, label)
    1.35 +        result = method(self, *args, **kwargs)
    1.36 +        if isinstance(result, Deferred):
    1.37 +            result.addCallback(end, label)
    1.38 +        else:
    1.39 +            end(None, label)
    1.40 +        return result
    1.41 +
    1.42 +    return profile_wrapper
    1.43 +
    1.44  if __name__ == "__main__":
    1.45      import doctest    #pragma NO COVER
    1.46      doctest.testmod() #pragma NO COVER