Context manager to measure execution time of a block

    :arg function metric: f(name, 1, time)
    :arg str name: name for the metric
    :arg int count: user-supplied number of items, defaults to 1
358764
def block(*, name = None, metric = call_default, count = 1):
    
    t = time.time()
    try:
        yield
    finally:
        metric(name, count, time.time() - t)
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
737448
def timeit(func):
    
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        start  = timer()
        result = func(*args, **kwargs)
        cost   = timer() - start
        logger.debug('<method: %s> finished in %2.2f sec' % (func.__name__, cost))
        return result
    return wrapped_func
154024
def function_call_with_timeout(fun_name, fun_args, secs=5):
    """"""
    from multiprocessing import Process, Queue
    p = Process(target=fun_name, args=tuple(fun_args))
    p.start()
    curr_secs = 0
    no_timeout = False
    if secs == 0: no_timeout = True
    else: timeout = secs
    while p.is_alive() and not no_timeout:
        if curr_secs > timeout:
            print("Process time has exceeded timeout, terminating it.")
            p.terminate()
            return False
        time.sleep(0.1)
        curr_secs += 0.1
    p.join() # Blocks if process hasn't terminated.
    return True
490548
def timeit(func):
    '''
    
    '''

    def wapper(*args, **kwargs):
        _start = time.time()
        retval = func(*args, **kwargs)
        _end = time.time()
        logger.info('function %s() used : %.6f s' % (func.__name__, _end - _start))
        return retval

    return wapper
199934
def _process_batch(self, param, dataframe):
        
        now = time.time()
        if param.eval_metric is not None:
            metrics = dict(param.eval_metric.get_name_value())
            param.eval_metric.reset()
        else:
            metrics = {}
        # #11504
        try:
            speed = self.frequent / (now - self.last_time)
        except ZeroDivisionError:
            speed = float('inf')
        metrics['batches_per_sec'] = speed * self.batch_size
        metrics['records_per_sec'] = speed
        metrics['elapsed'] = self.elapsed()
        metrics['minibatch_count'] = param.nbatch
        metrics['epoch'] = param.epoch
        self.append_metrics(metrics, dataframe)
        self.last_time = now
1047822
def make_log_metric(level=logging.INFO, msg="%d items in %.2f seconds"):
    
    def log_metric(name, count, elapsed):
        log_name = 'instrument.{}'.format(name) if name else 'instrument'
        logging.getLogger(log_name).log(level, msg, count, elapsed)
    return log_metric
616324
def do_metric_list(mc, args):
    ''''''
    fields = {}
    if args.name:
        fields['name'] = args.name
    if args.dimensions:
        fields['dimensions'] = utils.format_dimensions_query(args.dimensions)
    if args.limit:
        fields['limit'] = args.limit
    if args.offset:
        fields['offset'] = args.offset
    if args.starttime:
        _translate_starttime(args)
        fields['start_time'] = args.starttime
    if args.endtime:
        fields['end_time'] = args.endtime
    if args.tenant_id:
        fields['tenant_id'] = args.tenant_id

    try:
        metric = mc.metrics.list(**fields)
    except (osc_exc.ClientException, k_exc.HttpError) as he:
        raise osc_exc.CommandError('%s\n%s' % (he.message, he.details))
    else:
        if args.json:
            print(utils.json_formatter(metric))
            return
        cols = ['name', 'dimensions']
        formatters = {
            'name': lambda x: x['name'],
            'dimensions': lambda x: utils.format_dict(x['dimensions']),
        }
        if isinstance(metric, list):
            # print the list
            utils.print_list(metric, cols, formatters=formatters)
        else:
            # add the dictionary to a list, so print_list works
            metric_list = list()
            metric_list.append(metric)
            utils.print_list(
                metric_list,
                cols,
                formatters=formatters)
731448
def timeit(argument):
    
    if hasattr(argument, 'info'):
        def decorator(function):
            @wraps(function)
            def wrapper(*args, **kwargs):
                start_time = time.time()
                argument.info('function [%s] start at [%s]' % (function.__name__, now(obj=False, precise=True)))
                rst = function(*args, **kwargs)
                argument.info('function [%s] exit  at [%s]' % (function.__name__, now(obj=False, precise=True)))
                argument.info('function [%s] coast [%sms]' % (function.__name__, (time.time() - start_time) * 1000))
                return rst

            return wrapper

        return decorator
    if callable(argument):
        @wraps(argument)
        def wrapper(*args, **kwargs):
            start_time = time.time()
            print 'function [%s] start at [%s]' % (argument.__name__, now(obj=False, precise=True))
            rst = argument(*args, **kwargs)
            print 'function [%s] exit  at [%s]' % (argument.__name__, now(obj=False, precise=True))
            print 'function [%s] coast [%sms]' % (argument.__name__, (time.time() - start_time) * 1000)
            return rst

        return wrapper
    raise ValueError('argument error.')
963188
private Map<MetricName, MetricValue> get_metrics_(DateTime now, Context ctx) {
        final Consumer<Alert> alert_manager = ctx.getAlertManager();
        final long failed_collections = registry_.getFailedCollections();
        final boolean has_config = registry_.hasConfig();
        final Optional<Duration> scrape_duration = registry_.getScrapeDuration();
        final Optional<Duration> rule_eval_duration = registry_.getRuleEvalDuration();
        final Optional<Duration> processor_duration = registry_.getProcessorDuration();
        first_scrape_ts_.compareAndSet(null, now);  // First time, register the timestamp.
        final Duration uptime = new Duration(first_scrape_ts_.get(), now);

        final Optional<DateTime> last_scrape = last_scrape_;
        last_scrape_ = Optional.of(now);

        final long metric_count = ctx.getTSData().getCurrentCollection().getTSValues().stream()
                .map(TimeSeriesValue::getMetrics)
                .collect(Collectors.summingLong(Map::size));

        alert_manager.accept(new Alert(now, MONITOR_FAIL_ALERT, () -> "builtin rule", Optional.of(failed_collections != 0), MON_ALERT_DURATION, "builtin rule: some collectors failed", EMPTY_MAP));
        alert_manager.accept(new Alert(now, HAS_CONFIG_ALERT, () -> "builtin rule", Optional.of(!has_config), Duration.ZERO, "builtin rule: monitor has no configuration file", EMPTY_MAP));

        Map<MetricName, MetricValue> result = new HashMap<>();
        result.put(FAILED_COLLECTIONS_METRIC, MetricValue.fromIntValue(failed_collections));
        result.put(GROUP_COUNT_METRIC, MetricValue.fromIntValue(ctx.getTSData().getCurrentCollection().getGroups(x -> true).size()));
        result.put(METRIC_COUNT_METRIC, MetricValue.fromIntValue(metric_count));
        result.put(CONFIG_PRESENT_METRIC, MetricValue.fromBoolean(has_config));
        result.put(SCRAPE_DURATION, opt_duration_to_metricvalue_(scrape_duration));
        result.put(RULE_EVAL_DURATION, opt_duration_to_metricvalue_(rule_eval_duration));
        result.put(PROCESSOR_DURATION, opt_duration_to_metricvalue_(processor_duration));
        result.put(UPTIME_DURATION, duration_to_metricvalue_(uptime));
        result.put(SCRAPE_COUNT, MetricValue.fromIntValue(++scrape_count_));
        result.put(SCRAPE_INTERVAL, opt_duration_to_metricvalue_(last_scrape.map(prev -> new Duration(prev, now))));
        result.put(SCRAPE_TS, MetricValue.fromIntValue(now.getMillis()));
        return result;
    }
479278
def stderr_metric(name, count, elapsed):
    
    _do_print(name, count, elapsed, file=sys.stderr)
683108
def run_timed(self, **kwargs):
        
        for key in kwargs:
            setattr(self, key, kwargs[key])
        self.command = self.COMMAND_RUN_TIMED
1081914
def timestamp(self, name, value):
        
        for counter in self._counters:
            counter.timestamp(name, value)
797894
def _emit_metrics(self, missing_datetimes, finite_start, finite_stop):
        
        datetimes = self.finite_datetimes(
            finite_start if self.start is None else min(finite_start, self.parameter_to_datetime(self.start)),
            finite_stop if self.stop is None else max(finite_stop, self.parameter_to_datetime(self.stop)))

        delay_in_jobs = len(datetimes) - datetimes.index(missing_datetimes[0]) if datetimes and missing_datetimes else 0
        self.trigger_event(RangeEvent.DELAY, self.of_cls.task_family, delay_in_jobs)

        expected_count = len(datetimes)
        complete_count = expected_count - len(missing_datetimes)
        self.trigger_event(RangeEvent.COMPLETE_COUNT, self.of_cls.task_family, complete_count)
        self.trigger_event(RangeEvent.COMPLETE_FRACTION, self.of_cls.task_family, float(complete_count) / expected_count if expected_count else 1)
412475
def timed(function):
    """"""
    @wraps(function)
    def function_wrapper(obj, *args, **kwargs):
        """Wrapper function printing the time taken by the call to `function`"""
        name = obj.__class__.__name__ + '.' + function.__name__
        start = time.clock()
        result = function(obj, *args, **kwargs)
        print('{}: {:.4f} seconds'.format(name, time.clock() - start))
        return result
    return function_wrapper
1204866
def timing(function):
    '''
    
    '''
    @wraps(function)
    def wrapped(*args, **kwargs):
        start_time = time.time()
        ret = function(*args, **salt.utils.args.clean_kwargs(**kwargs))
        end_time = time.time()
        if function.__module__.startswith('salt.loaded.int.'):
            mod_name = function.__module__[16:]
        else:
            mod_name = function.__module__
        fstr = 'Function %s.%s took %.{0}f seconds to execute'.format(
            sys.float_info.dig
        )
        log.profile(fstr, mod_name, function.__name__, end_time - start_time)
        return ret
    return wrapped
398245
def timeit (func, log, limit):
    """"""

    def newfunc (*args, **kwargs):
        """Execute function and print execution time."""
        t = time.time()
        res = func(*args, **kwargs)
        duration = time.time() - t
        if duration > limit:
            print(func.__name__, "took %0.2f seconds" % duration, file=log)
            print(args, file=log)
            print(kwargs, file=log)
        return res
    return update_func_meta(newfunc, func)