[PATCH 2 of 6 v2] util: add an elapsed time wrapper

Simon Farnsworth simonfar at fb.com
Thu Feb 2 14:18:56 EST 2017


# HG changeset patch
# User Simon Farnsworth <simonfar at fb.com>
# Date 1486063056 28800
#      Thu Feb 02 11:17:36 2017 -0800
# Node ID 12d0ac224bb34691d44a2cead5b9795a6cfc2490
# Parent  f443bd95a948aaed36e81edb884085fc2f0f5acf
util: add an elapsed time wrapper

We want to log the time spent in various commands. Add a wrapper class that
can be used to measure time taken by a function or all members of a class

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -3543,3 +3543,38 @@
 
 # convenient shortcut
 dst = debugstacktrace
+
+class elapsedtimewrapper(object):
+    def __init__(self, orig):
+        self.__orig = orig
+        self.__istiming = False
+        self.counttime = True
+        self.elapsedms = 0
+
+    def __call__(self, *args, **kwargs):
+        if self.counttime:
+            return self.__time(self.__orig, *args, **kwargs)
+        else:
+            return self.__orig(*args, **kwargs)
+
+    def __getattr__(self, name):
+        origattr = getattr(self.__orig, name)
+        if self.counttime and callable(origattr):
+            def closure(*args, **kwargs):
+                return self.__time(origattr, *args, **kwargs)
+            return closure
+        else:
+            return origattr
+
+    def __time(self, func, *args, **kwargs):
+        if self.__istiming:
+            return func(*args, **kwargs)
+
+        start = time.time()
+        try:
+            self.__istiming = True
+            return func(*args, **kwargs)
+        finally:
+            duration = time.time() - start
+            self.elapsedms += duration * 1000
+            self.__istiming = False


More information about the Mercurial-devel mailing list