changeset 40144:acf560bc9b56

perf: extract the timing of a section in a context manager This makes it easier to reuse it in other (future) part of the code that requires their own time management.
author Boris Feld <boris.feld@octobus.net>
date Tue, 02 Oct 2018 18:54:06 +0200
parents d5d28d360a19
children 21261fc0fb2b
files contrib/perf.py
diffstat 1 files changed, 16 insertions(+), 7 deletions(-) [+]
line wrap: on
line diff
--- a/contrib/perf.py	Mon Oct 01 17:23:54 2018 +0200
+++ b/contrib/perf.py	Tue Oct 02 18:54:06 2018 +0200
@@ -19,6 +19,7 @@
 #   Mercurial
 
 from __future__ import absolute_import
+import contextlib
 import functools
 import gc
 import os
@@ -273,20 +274,28 @@
 def stub_timer(fm, func, title=None):
     func()
 
+@contextlib.contextmanager
+def timeone():
+    r = []
+    ostart = os.times()
+    cstart = util.timer()
+    yield r
+    cstop = util.timer()
+    ostop = os.times()
+    a, b = ostart, ostop
+    r.append((cstop - cstart, b[0] - a[0], b[1]-a[1]))
+
 def _timer(fm, func, title=None, displayall=False):
     gc.collect()
     results = []
     begin = util.timer()
     count = 0
     while True:
-        ostart = os.times()
-        cstart = util.timer()
-        r = func()
+        with timeone() as item:
+            r = func()
+        count += 1
+        results.append(item[0])
         cstop = util.timer()
-        ostop = os.times()
-        count += 1
-        a, b = ostart, ostop
-        results.append((cstop - cstart, b[0] - a[0], b[1]-a[1]))
         if cstop - begin > 3 and count >= 100:
             break
         if cstop - begin > 10 and count >= 3: