view MoinMoin/util/ @ 1764:19b19d4d9291

Add a @timed decorator. The decorator adds flaskg.clock.{start,stop} calls to entrance and exit of a function.
author Cheer Xiao <>
date Sat, 01 Sep 2012 20:53:20 +0800
parents 4ac437141bbe
children 384555088cab
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 MoinMoin import log
logging = log.getLogger(__name__)

from flask import g as flaskg

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)