Patchwork [3,of,5] util: add an elapsed time wrapper

login
register
mail settings
Submitter Simon Farnsworth
Date Jan. 19, 2017, 7:02 p.m.
Message ID <e8cd90ea5d3eee923304.1484852529@devvm022.lla2.facebook.com>
Download mbox | patch
Permalink /patch/18263/
State Deferred
Headers show

Comments

Simon Farnsworth - Jan. 19, 2017, 7:02 p.m.
# HG changeset patch
# User Simon Farnsworth <simonfar@fb.com>
# Date 1484849321 28800
#      Thu Jan 19 10:08:41 2017 -0800
# Node ID e8cd90ea5d3eee923304c64a19c3be9bce50451c
# Parent  d444a9f4d468b7a0705d48b2f4f84c7bd44b6c74
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

Patch

diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -3254,3 +3254,35 @@ 
 
 # 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):
+        return self.__time(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