pun not intended

        # TODO: record iteration times for analysis
        # TODO Incorporate this better
        # FIXME; pad_stdout into subfunctions

        import dis
        dis.dis(ut.ProgressIter.iter_rate)
5030
def iter_rate(self):
        
        #class IterState(object):
        #    def __init__(state):
        #        state.freq = 1
        #        state.freq = 1
        #        pass
        adjust = self.autoadjust
        self._cursor_at_newline = not self.backspace
        # SETUP VARIABLES
        # HACK: reaquire logging print funcs in case they have changed
        if self.stream is None:
            self.write = util_logging._utool_write()
            self.flush = util_logging._utool_flush()
        else:
            self.write = lambda msg: self.stream.write(msg)  # NOQA
            self.flush = lambda: self.stream.flush()  # NOQA

        length        = self.length * self.parent_length  # hack
        freq          = self.freq
        self.count    = 0
        between_count = 0
        last_count    = 0

        # how long iterations should be before a flush
        # (used for freq adjustment)
        time_thresh = (self._get_timethresh_heuristics()
                       if self.time_thresh is None else
                       self.time_thresh)
        time_thresh_growth = self.time_thresh_growth
        if time_thresh_growth > 1:
            # time_thresh_growth is specified for very long processes
            # print out the starting timestamp in that case
            timestamp = time.strftime('%Y-%m-%d %H:%M:%S') + ' ' + time.tzname[0]
            print('Start progress lbl= %s at %s' % (self.lbl, timestamp,))
        #time_thresh = 0.5
        max_between_time = -1.0
        max_between_count = -1.0  # why is this different? # because frequency varies

        # TODO: should be kept as a statistic that uses the max time from a
        # list of iterations divided by the size of that list that will account
        # for buffering issues
        iters_per_second = 0
        self.iters_per_second = float('nan')
        self.est_seconds_left = 0
        self.total_seconds = 0

        # Write initial message
        #force_newlines = not self.backspace
        start_msg_fmt = ''.join(self.build_msg_fmtstr_head_cols(length, self.lbl))
        self.msg_fmtstr = self.build_msg_fmtstr2(self.lbl, length,
                                                 self.invert_rate,
                                                 self.backspace)

        try:
            util_logging._utool_flush()()
        except IOError as ex:
            # There is some weird error when doing progress in IPython notebook
            if util_arg.VERBOSE:
                print('IOError flushing %s' % (ex,))
        if not self.prehack:
            if self.backspace:
                self.display_message()
            elif self.verbose:
                start_msg = start_msg_fmt.format(count=self.parent_offset)
                util_logging._utool_write()(start_msg + '\n')

            self._cursor_at_newline = not self.backspace

            try:
                util_logging._utool_flush()()
            except IOError as ex:
                # There is some weird error when doing progress in IPython notebook
                if util_arg.VERBOSE:
                    print('IOError flushing %s' % (ex,))
        else:
            self._cursor_at_newline = True

        if self.prog_hook is not None:
            self.prog_hook(self.count, length)

        # TODO: on windows is time.clock better?
        # http://exnumerus.blogspot.com/2011/02/how-to-quickly-plot-multiple-line.html
        start_time    = default_timer()
        last_time     = start_time

        start = 1 + self.parent_offset

        if self.freq_est_strat == 'between':
            FREQ_EST = 0
        elif self.freq_est_strat == 'absolute':
            FREQ_EST = 1
        else:
            FREQ_EST = 1

        USE_RECORD = True

        # use last 64 times to compute a more stable average rate
        measure_between_time = collections.deque([], maxlen=self.est_window)

        # Wrap the for loop with a generator
        for self.count, item in enumerate(self.iterable, start=start):
            if self.prehack:
                # hack to print before yeilding
                # so much for efficiency
                self.set_extra((self.lbl + '=' + self.prehack) % item)
                self.display_message()
                self.ensure_newline()

            # GENERATE
            yield item

            if self.prehack or (self.count) % freq == 0:
                now_time          = default_timer()
                between_time      = (now_time - last_time)
                between_count     = self.count - last_count
                total_seconds     = (now_time - start_time)
                self.total_seconds = total_seconds
                if FREQ_EST == 0:
                    if USE_RECORD:
                        measure_between_time.append(between_count / (float(between_time) + 1E-9))
                        iters_per_second = sum(measure_between_time) / len(measure_between_time)
                    else:
                        iters_per_second = between_count / (float(between_time) + 1E-9)
                elif FREQ_EST == 1:
                    iters_per_second = (now_time - start_time) / self.count

                self.iters_per_second = iters_per_second
                # If the future is known
                if length is None:
                    est_seconds_left = -1
                else:
                    iters_left = length - self.count
                    est_seconds_left = iters_left / (iters_per_second + 1E-9)
                self.est_seconds_left = est_seconds_left

                # /future
                last_count        = self.count
                last_time         = now_time
                # ADJUST FREQ IF NEEDED
                # Adjust frequency if printing too quickly
                # so progress doesnt slow down actual function
                # TODO: better adjust algorithm
                time_thresh *= time_thresh_growth
                if adjust and (between_time < time_thresh or between_time > time_thresh * 2.0):
                    max_between_time = max(max(max_between_time, between_time),
                                           1E-9)
                    max_between_count = max(max_between_count, between_count)
                    # If progress was uniform and all time estimates were
                    # perfect this would be the new freq to achieve time_thresh
                    new_freq = max(int(time_thresh * max_between_count /
                                       max_between_time), 1)
                    if DEBUG_FREQ_ADJUST:
                        print('\n+---')
                        print('[prog] between_count = %r' % between_count)
                        print('[prog] between_time = %.8r' % between_time)
                        print('[prog] time_thresh = %r' % time_thresh)
                        print('[prog] max_between_count = %r' % max_between_count)
                        print('[prog] max_between_time = %.8r' % max_between_time)
                        print('[prog] Adusting frequency from: %r' % freq)
                        print('[prog] Adusting frequency to: %r' % new_freq)
                        print('L___')
                    # But things are not perfect. So, don't make drastic changes
                    max_freq_change_up = max(256, freq * 2)
                    max_freq_change_down = freq // 2
                    if (new_freq - freq) > max_freq_change_up:
                        freq += max_freq_change_up
                    elif (freq - new_freq) > max_freq_change_down:
                        freq -= max_freq_change_down
                    else:
                        freq = new_freq

                if not self.prehack:
                    self.display_message()

                # DO PROGRESS INFO
                if self.prog_hook is not None:
                    # From the point of view of the progress iter, we are about
                    # to enter the body of a for loop. (But we may have
                    # executed the body implicitly in the yeild....  so it is
                    # ambiguous. In the second case 0 will be executed twice.
                    self.prog_hook(self.count, length)

        if self.prehack:
            self.set_extra('')

        # --- end of main loop
        # cleanup
        if (self.count) % freq != 0:
            # If the final line of progress was not written in the loop, write
            # it here
            self.est_seconds_left = 0
            self.total_seconds = (default_timer() - start_time)
            self.display_message()
            if self.prog_hook is not None:
                # From the point of view of the progress iter, we are about to
                # enter the body of a for loop. (But we may have executed the
                # body implicitly in the yeild....  so it is ambiguous. In the
                # second case 0 will be executed twice.
                self.prog_hook(self.count, length)

        self.ensure_newline()
479278
def stderr_metric(name, count, elapsed):
    
    _do_print(name, count, elapsed, file=sys.stderr)
631385
def timing(rounds=1, limit=None):
    '''
    
    '''
    def decorator(method):
        @functools.wraps(method)
        def f():
            if rounds == 1:
                start = time.time()
                method()
                duration = time.time() - start
            else:
                start = time.time()
                for i in range(rounds):
                    method()
                duration = (time.time() - start) / rounds
            # Use milliseconds for duration counter
            duration = duration * 1e3

            print('Test "%s.%s" took %.06f ms.' % (method.__module__, method.__name__, duration))
            if limit is not None:
                assert limit > duration, 'Timing failure: %.06f > %.06f' % (duration, limit)

        # Run tests with timings, only if WITH_TIMINGS environment variable is set.
        # This is because tests with multiple rounds can take long to process.
        if environ.get('WITH_TIMINGS', None) == '1':
            return f
        return method
    return decorator
177252
def console_progress():
    
    def progress(totalhashed, totalsize):
        "Helper"
        msg = " " * 30
        if totalhashed < totalsize:
            msg = "%5.1f%% complete" % (totalhashed * 100.0 / totalsize)
        sys.stdout.write(msg + " \r")
        sys.stdout.flush()

    try:
        return progress if sys.stdout.isatty() else None
    except AttributeError:
        return None
1092228
def print_stats
      fmh = " %-20s | %10s | %5s | %6s | %6s | %6s | %-20s\n"
      fmt = " %-20s | %10.3f | %5i | %6.3f | %6.3f | %6.3f | %s\n"
      head = sprintf(fmh, 
                     "class", "total", "count", "min", "max", "avg", "callers")
      line = "-" * head.length  
      puts line
      print head
      puts line
      @loading_stats.sort_by { |key, val| 
        val[:total_time] 
      }.reverse.each { |key, val|
        key = key.to_s
        if(key.length > 20)
          key = key[-20,20]
        end
        avg = val[:total_time] / val[:count]
        printf(fmt, key, val[:total_time], val[:count],
               val[:times].min, val[:times].max, avg,
               val[:callers].join(','))
      }
      puts line
      $stdout.flush
    end
412702
def demo_err():
    
    max_order = 7
    n = 20
    l = 0.25
    fmt1 = '{0: <5s}\t{1: <21s}\t{2: >21s}\t{3: >21s}\t{4: >21s}'
    fmt2 = '{0: <5d}\t{1:20.18f}\t{2: >21.18f}\t{3: >21.18f}\t{4: >21.18f}'
    x = np.cumsum(np.random.rand(n)*l)
    x = np.concatenate((x[::-1]*-1, x))
    lst = []
    derivs = np.zeros(n)
    for order in range(max_order+1):
        print('Order', order)
        for m in range(1+order//2, n+1):
            sub_x = x[n-m:n+m]
            derivs[m-1] = derivatives_at_point_by_finite_diff(
                sub_x, np.exp(sub_x), 0, order)[order]
        print(fmt1.format('m', 'val', 'diff', 'analytical error',
                          'diff/analytical'))
        for m in range(1, n):
            print(fmt2.format(
                (m+1)*2, derivs[m], derivs[m]-derivs[m-1],
                derivs[m]-1, (derivs[m]-derivs[m-1])/(derivs[m]-1)))
        lst.append((derivs[-1], abs(derivs[-1]-derivs[-2])))
    print(np.array(lst))
507867
function benchmark( b ) {
		var i;

		b.tic();
		for ( i = 0; i < b.iterations; i++ ) {
			// TODO: synchronous task
			if ( TODO/* TODO: condition */ ) {
				b.fail( 'something went wrong' );
			}
		}
		b.toc();
		if ( TODO/* TODO: condition */ ) {
			b.fail( 'something went wrong' );
		}
		b.pass( 'benchmark finished' );
		b.end();
	}
233715
def iter_duration(self, iter_trigger):
        
        print
        process_info = ProcessInfo(self.frame_count, use_last_rates=4)
        start_time = time.time()
        next_status = start_time + 0.25

        old_pos = next(iter_trigger)
        for pos in iter_trigger:
            duration = pos - old_pos
#             log.log(5, "Duration: %s" % duration)
            yield duration
            old_pos = pos

            if time.time() > next_status:
                next_status = time.time() + 1
                self._print_status(process_info)

        self._print_status(process_info)
        print
207552
def iteration_length(N, start=0, step=1):
    '''
    '''
    if N < 0:
        raise ValueError('N cannot be negative')

    if start < 0:
        start += N
        if start < 0:
            raise ValueError('Invalid start value')

    if step < 0:
        step = -step
        new_N = start + 1
        if new_N > N:
            raise ValueError('Invalid parameters')
        N = new_N
        start = 0

    ret = int(math.ceil((N - start) / float(step)))
    return max(0, ret)
516193
def _on_iteration(self, *args, **kwargs) -> None:
        

        # Update timing and the iteration number in the monitoring context.
        current_timestamp = get_hr_time()
        self._context.optimisation_time += current_timestamp - self._last_timestamp
        self._context.total_time = current_timestamp - self._start_timestamp
        self._context.optimiser_updated = False
        if not self._context.optimisation_finished:
            self._context.iteration_no += 1

        # Call all monitoring functions
        for func in self._monitor_tasks:
            func(self._context, *args, **kwargs)

        # Remember the time when the control is returned back to the optimiser, so that the next
        # optimisation step can be accurately timed.
        self._last_timestamp = get_hr_time()
775604
def _show_stat_wrapper_multi_Progress(count, last_count, start_time, max_count, speed_calc_cycles, 
                                      width, q, last_speed, prepend, show_stat_function, len_, 
                                      add_args, lock, info_line, no_move_up=False):
    
#         print(ESC_BOLD, end='')
#         sys.stdout.flush()
    for i in range(len_):
        _show_stat_wrapper_Progress(count[i], last_count[i], start_time[i], max_count[i], speed_calc_cycles, 
                                    width, q[i], last_speed[i], prepend[i], show_stat_function,
                                    add_args, i, lock[i])
    n = len_
    if info_line is not None:
        s = info_line.value.decode('utf-8')
        s = s.split('\n')
        n += len(s)
        for si in s:
            if width == 'auto':
                width = get_terminal_width()
            if len(si) > width:
                si = si[:width]
            print("{0:<{1}}".format(si, width))
    
    if no_move_up:
        n = 0
                                # this is only a hack to find the end
                                # of the message in a stream
                                # so ESC_HIDDEN+ESC_NO_CHAR_ATTR is a magic ending
    print(terminal.ESC_MOVE_LINE_UP(n) + terminal.ESC_MY_MAGIC_ENDING, end='')
    sys.stdout.flush()
922423
def iterprogress( sized_iterable ):
    
    pb = ProgressBar( 0, len( sized_iterable ) )
    for i, value in enumerate( sized_iterable ):
        yield value
        pb.update_and_print( i, sys.stderr )
351031
def log_benchmark(fn, start, end):
    
    elapsed = round(end - start, 2)
    line = ("Benchmark - Function: {} , Time: {} seconds".format(fn, elapsed))
    return line
427979
def progress(count, total, suffix=''):
    '''
    
    '''
    bar_len = 60
    filled_len = int(round(bar_len * count / float(total)))
    percents = round(100.0 * count / float(total), 1)
    bar = '=' * filled_len + '-' * (bar_len - filled_len)
    sys.stdout.write('[%s] %s%s %s\r' % (bar, percents, '%', suffix))
    sys.stdout.flush()
69729
def time_func(func, name, *args, **kwargs):
    
    tic = time.time()
    out = func(*args, **kwargs)
    toc = time.time()
    print('%s took %0.2f seconds' % (name, toc - tic))
    return out
355180
def stdout_to_results(s):
    """"""
    results = s.strip().split('\n')
    return [BenchmarkResult(*r.split()) for r in results]
220795
def _typeseq_iter(s):
    

    s = str(s)
    while s:
        t, s = _next_argsig(s)
        yield t