# -*- coding: utf-8 -*-
"""The NOOP timer module

Copyright © 2016, Anders Andersen, The Arctic University of Norway.
See http://www.cs.uit.no/~aa/dist/tools/noop/COPYING (../COPYING) for
details.

"""


# Import system modules
import time
from contextlib import contextmanager


class Timer:
    R"""A class for timing Python code

    An instance of the Timer class is used as a timer using a with
    statement.  See the following example:

    >>> timer = Timer(name=AES, output=sys.stdout)
    >>> with timer("Generate key"):
    >>>     key = AESKey()

    When the with block is done a message with the timer information
    will be printed.  The value (execution time) of the block will
    also be available as a float value at `timer.data["Generate key"]`.

    """

    def __init__(self, name=None, output=None,
                 fmt="{0:15s} {1:8.6f}",
                 ns="/", lbe=":", eol="\n"):
        self.name = name
        self.output = output
        self.fmt = fmt
        self.ns = ns
        self.lbe = lbe
        self.eol = eol
        self.data = {}
            
    @contextmanager
    def __call__(self, label):
        start = time.clock()
        try:
            yield
        finally:
            end = time.clock()
            self.data[label] = end-start
            if self.output:
                msg = ""
                if self.name:
                    msg += self.name + self.ns
                msg += self.fmt.format(label + self.lbe, self.data[label])
                self.output.write(msg + self.eol)

