view MoinMoin/util/ @ 2960:b2417a0dd48f tip

trivial change to prevent traceback when 0 is passed to TableOfContents macro
author RogerHaase <>
date Thu, 18 Jun 2015 15:31:51 -0700
parents da84a2c42a92
line wrap: on
line source
# Copyright: 2001-2003 Juergen Hermann <>
# Copyright: 2003-2006 MoinMoin:ThomasWaldmann
# License: GNU GPL v2 (or any later version), see LICENSE.txt for details.

    MoinMoin - Clock

import time
from functools import wraps, partial

from flask import g as flaskg

from MoinMoin import log
logging = log.getLogger(__name__)

class Clock(object):
    Helper class for measuring the time needed to run code.

        # do something
        # or if you want to use its value later
        timerval = flaskg.clock.stop('mytimer')

    Starting a timer multiple times is supported but the
    one started last has to be stopped first.

    def __init__(self):
        self.timers = {}

    def start(self, timer):
        if timer not in self.timers:
            self.timers[timer] = []

    def stop(self, timer):
        if timer in self.timers:
            value = time.time() - self.timers[timer].pop()
  'timer {0}({1}): {2:.2f}ms'.format(timer, len(self.timers[timer]), value * 1000))
            if not self.timers[timer]:
                del self.timers[timer]
            return value

    def __del__(self):
        if self.timers:
            logging.warning('These timers have not been stopped: {0}'.format(', '.join(self.timers.keys())))

def add_timing(f, name=None):
    if name is None:
        name = f.__name__

    def wrapper(*args, **kw):
        retval = f(*args, **kw)
        return retval
    return wrapper

def timed(name=None):
    return partial(add_timing, name=name)