[PATCH 1 of 2 v2] utils: create a context manager to handle timing

Yuya Nishihara yuya at tcha.org
Thu Aug 2 08:01:08 EDT 2018


On Wed, 01 Aug 2018 17:29:39 +0200, Martijn Pieters wrote:
> # HG changeset patch
> # User Martijn Pieters <mj at zopatista.com>
> # Date 1533132341 -7200
> #      Wed Aug 01 16:05:41 2018 +0200
> # Branch stable
> # Node ID 2bad2ee57e26f05f99a81715e781f7978515b705
> # Parent  545a3e6650cd8f7e19c0f0256082837a33bea029
> # EXP-Topic debugextensions
> utils: create a context manager to handle timing

Queued, thanks.

> +from .utils import (
> +    procutil,
> +    stringutil,
> +)
>  from . import (
>      encoding,
>      error,
> @@ -45,10 +52,6 @@
>      pycompat,
>      urllibcompat,
>  )
> -from .utils import (
> -    procutil,
> -    stringutil,
> -)

Dropped this change since ".utils" are generally imported after ".".

> -_timenesting = [0]
> + at attr.s
> +class timedcmstats(object):
> +    """Stats information produced by the timedcm context manager on entering."""
> +
> +    # the starting value of the timer as a float (meaning and resulution is
> +    # platform dependent, see util.timer)
> +    start = attr.ib(default=attr.Factory(lambda: timer()))
> +    # the number of seconds as a floating point value; starts at 0, updated when
> +    # the context is exited.
> +    elapsed = attr.ib(default=0)
> +    # the number of nested timedcm context managers.
> +    level = attr.ib(default=1)
> +
> +    def __str__(self):
> +        return timecount(self.elapsed) if self.elapsed else '<unknown>'

Needs s/__str__/__bytes__/ and __str__ = encoding.strmethod(__bytes__) for py3.
Can you send a follow up?

> + at contextlib.contextmanager
> +def timedcm():
> +    """A context manager that produces timing information for a given context.
> +
> +    On entering a timedcmstats instance is produced.
> +
> +    This context manager is reentrant.
> +
> +    """
> +    # track nested context managers
> +    timedcm._nested += 1
> +    timing_stats = timedcmstats(level=timedcm._nested)
> +    try:
> +        yield timing_stats
> +    finally:
> +        timing_stats.elapsed = timer() - timing_stats.start
> +        timedcm._nested -= 1
> +
> +timedcm._nested = 0

This isn't thread safe, but is no worse than the original code.


More information about the Mercurial-devel mailing list