Log a given function and how long the function takes in seconds
    :param str fn: Function name
    :param float start: Function start time
    :param float end: Function end time
    :return none:
351031
def log_benchmark(fn, start, end):
    
    elapsed = round(end - start, 2)
    line = ("Benchmark - Function: {} , Time: {} seconds".format(fn, elapsed))
    return line
558322
def log_time(method):
    

    def timed(*args, **kwargs):
        tic = time_function()
        result = method(*args, **kwargs)
        log.debug('%s executed in %.4f seconds.',
                  method.__name__,
                  time_function() - tic)
        return result
    timed.__name__ = method.__name__
    timed.__doc__ = method.__doc__
    return timed
572770
def is_start_of_function(text):
    """"""
    if isinstance(text, str) or isinstance(text, unicode):
        function_prefix = ['def', 'async def']
        text = text.lstrip()

        for prefix in function_prefix:
            if text.startswith(prefix):
                return True

    return False
933812
def log_output(f):
    

    @wraps(f)
    def wrapper_fn(*args, **kwargs):
        res = f(*args, **kwargs)
        logging.debug("Logging result %s.", res)
        return res

    return wrapper_fn
1168839
def _timing(f, logs_every=100):
  """"""
  @functools.wraps(f)
  def wrap(*args, **kw):
    """The timer function."""
    ts = _time.time()
    result = f(*args, **kw)
    te = _time.time()
    qj._call_counts[f] += 1
    qj._timings[f] += (te - ts)
    count = qj._call_counts[f]
    if count % logs_every == 0:
      qj(x='%2.4f seconds' % (qj._timings[f] / count),
         s='Average timing for %s across %d call%s' % (f, count, '' if count == 1 else 's'), _depth=2)
    return result
  return wrap
383524
def timeit(func):
    

    @wraps(func)
    def timer_wrapper(*args, **kwargs):
        """
        Inner function that uses the Timer context object
        """
        with Timer() as timer:
            result = func(*args, **kwargs)

        return result, timer

    return timer_wrapper
811875
def time_calls_with_dims(**dims):
    """"""
    def time_wrapper(fn):
        @functools.wraps(fn)
        def fn_wrapper(*args, **kwargs):
            _timer = timer("%s_calls" %
                           pyformance.registry.get_qualname(fn), **dims)
            with _timer.time(fn=pyformance.registry.get_qualname(fn)):
                return fn(*args, **kwargs)
        return fn_wrapper
    return time_wrapper
676136
def _function(self):
        

        start_time = datetime.datetime.now()

        # calculate stop time
        if self.settings['wait_mode'] == 'absolute':
            stop_time = start_time + datetime.timedelta(seconds= self.settings['wait_time'])
        elif self.settings['wait_mode'] == 'loop_interval':
            if self.last_execution is None:
                stop_time = start_time
            else:
                loop_time = start_time - self.last_execution
                wait_time = datetime.timedelta(seconds= self.settings['wait_time'])
                if wait_time.total_seconds() <0:
                    stop_time = start_time
                else:
                    stop_time = start_time + wait_time
        else:
            TypeError('unknown wait_mode')

        current_time = start_time
        while current_time<stop_time:
            if self._abort:
                break
            current_time = datetime.datetime.now()

            time.sleep(1)

            self.progress = 100.*(current_time- start_time).total_seconds() / (stop_time - start_time).total_seconds()
            self.updateProgress.emit(int(self.progress))

        if self.settings['wait_mode'] == 'absolute':
            self.last_execution = None
        else:
            self.last_execution = start_time
302194
def log_time(func):
    

    @functools.wraps(func)
    def _execute(*args, **kwargs):
        """Executes function and logs time

        :param args: args of function
        :param kwargs: extra args of function
        :param *args: args
        :param **kwargs: extra args
        :return: function result
        """

        func_name = get_method_name(func)
        timer = Timer()
        log_message(func_name, "has started")

        with timer:
            result = func(*args, **kwargs)

        seconds = "{:.3f}".format(timer.elapsed_time())
        log_message(func_name, "has finished. Execution time:", seconds, "s")

        return result

    return _execute
924033
def run_func(self, func, load):
        '''
        
        '''
        # Don't honor private functions
        if func.startswith('__'):
            # TODO: return some error? Seems odd to return {}
            return {}, {'fun': 'send'}
        # Run the func
        if hasattr(self, func):
            try:
                start = time.time()
                ret = getattr(self, func)(load)
                log.trace(
                    'Master function call %s took %s seconds',
                    func, time.time() - start
                )
            except Exception:
                ret = ''
                log.error('Error in function %s:\n', func, exc_info=True)
        else:
            log.error(
                'Received function %s which is unavailable on the master, '
                'returning False', func
            )
            return False, {'fun': 'send'}
        # Don't encrypt the return value for the _return func
        # (we don't care about the return value, so why encrypt it?)
        if func == '_return':
            return ret, {'fun': 'send'}
        if func == '_pillar' and 'id' in load:
            if load.get('ver') != '2' and self.opts['pillar_version'] == 1:
                # Authorized to return old pillar proto
                return ret, {'fun': 'send'}
            return ret, {'fun': 'send_private', 'key': 'pillar', 'tgt': load['id']}
        # Encrypt the return
        return ret, {'fun': 'send'}
825269
def log_start_end(f):
    
    def inner(f, *args, **kwargs):
        logging.info('Starting %s' % f.__name__)
        res = f(*args, **kwargs)
        logging.info('Finished %s' % f.__name__)
        return res
    return decorator.decorator(inner, f)
139196
def seconds(num):
    
    now = pytime.time()
    end = now + num
    until(end)
1202019
def timethis(func):
    """"""
    func_module, func_name = func.__module__, func.__name__

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = _time_perf_counter()
        r = func(*args, **kwargs)
        end = _time_perf_counter()
        print('timethis : <{}.{}> : {}'.format(func_module, func_name, end - start))
        return r
    return wrapper
734298
def time_func(func):
    
    def timed(*args, **kwargs):
        ts = time.time()
        result = func(*args, **kwargs)
        secs = time.time() - ts
        ops_ps = kwargs.get('operations', secs) / secs
        print ("finc{} took: {} {:2.4f} operations/sec={:5.2f}".format(func.__name__, seconds_to_DHMS(secs), secs, ops_ps))
        return result
    return timed
525454
def make_relative_timing_fn():
  """"""
  start_time = time.time()

  def format_relative_time():
    time_delta = time.time() - start_time
    return str(datetime.timedelta(seconds=time_delta))

  def log_relative_time():
    tf.logging.info("Timing: %s", format_relative_time())

  return log_relative_time
1152426
def timed_do_fn(f):
    """"""
    def wrap(callable, *args, **kwargs):
        global _debug_id

        # get a description of the function that called us
        st = traceback.extract_stack(limit=2)
        file, line, name, _ = st[0]

        # and its locals
        frame = inspect.currentframe()
        locals = frame.f_locals

        # invent a unique ID for the description
        id, _debug_id = _debug_id, _debug_id + 1

        descr = "%s-%08x" % (name, id)

        start_time = time.time()
        log.msg("%s - before ('%s' line %d)" % (descr, file, line))
        for name in locals:
            if name in ('self', 'thd'):
                continue
            log.msg("%s -   %s = %r" % (descr, name, locals[name]))

        # wrap the callable to log the begin and end of the actual thread
        # function
        def callable_wrap(*args, **kargs):
            log.msg("%s - thd start" % (descr,))
            try:
                return callable(*args, **kwargs)
            finally:
                log.msg("%s - thd end" % (descr,))
        d = f(callable_wrap, *args, **kwargs)

        @d.addBoth
        def after(x):
            end_time = time.time()
            elapsed = (end_time - start_time) * 1000
            log.msg("%s - after (%0.2f ms elapsed)" % (descr, elapsed))
            return x
        return d
    wrap.__name__ = f.__name__
    wrap.__doc__ = f.__doc__
    return wrap
197583
def timeout(seconds=10, default_output='default_output'):
    
    def decorator(func):
        def _handle_timeout(signum, frame):
            """ throw the custom TimeoutError if called """
            raise TimeoutError(strerror(ETIME))

        def wrapper(*args, **kwargs):
            """ main wrapper for the error """
            # set up the propper error signal
            signal(SIGALRM, _handle_timeout)
            # set the time the function has to run
            alarm(seconds)
            try:
                result = func(*args, **kwargs)
            except TimeoutError:
                if default_output == 'default_output':
                    raise
                else:
                    result = default_output
            finally:
                # cancel the timer
                alarm(0)
            return result

        return wraps(func)(wrapper)
    return decorator