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 wrap: on
line diff
--- a/viff/util.py	Tue Sep 23 11:33:35 2008 +0200
+++ b/viff/util.py	Wed Oct 01 11:02:26 2008 +0200
@@ -25,6 +25,7 @@
 __docformat__ = "restructuredtext"
 
 import os
+import time
 import random
 import warnings
 from twisted.internet.defer import Deferred, succeed, gatherResults
@@ -249,6 +250,35 @@
     return long(p)
 
 
+PHASES = {}
+
+def begin(result, phase):
+    PHASES[phase] = time.time()
+    return result
+
+def end(result, phase):
+    stop = time.time()
+    start = PHASES.pop(phase, stop)
+    print "%s from %f to %f (%f sec)" % (phase, start, stop, stop - start)
+    return result
+
+def profile(method):
+    if not os.environ.get('VIFF_PROFILE'):
+        return method
+
+    @wrapper(method)
+    def profile_wrapper(self, *args, **kwargs):
+        label = "%s-%s" % (method.__name__, self.program_counter)
+        begin(None, label)
+        result = method(self, *args, **kwargs)
+        if isinstance(result, Deferred):
+            result.addCallback(end, label)
+        else:
+            end(None, label)
+        return result
+
+    return profile_wrapper
+
 if __name__ == "__main__":
     import doctest    #pragma NO COVER
     doctest.testmod() #pragma NO COVER