def pytime_statement(stmt, global_dict=None, Tmax=2.0,
                    repeat_count=128):
  """
  Determine time to execute statement (or block) of Python code.

  Here global_dict is the globals dict used for exec, Tmax is the max
  time to spend in pytime_statement(), in sec, and repeat_count is the
  number of times to paste stmt into the inner timing loop (this is
  automatically set to 1 if stmt takes too long).
  """
  if global_dict is None:
    global_dict = globals()

  ns = {}
  code = 'def timed_func():' + ('\n' +
         '\n'.join(['  '+x for x in stmt.split('\n')]))
  exec code in global_dict, ns

  start = clock()
  ns['timed_func']()
  T = clock() - start

  if T >= Tmax/4.0:
    return T
  elif T >= Tmax/4.0/repeat_count:
    return pytime(ns['timed_func'], (), {}, Tmax-T)
  else:
    code = 'def timed_func():' + ('\n' +
           '\n'.join(['  '+x for x in stmt.split('\n')]))*repeat_count
    exec code in global_dict, ns
    return pytime(ns['timed_func'], (), {}, Tmax-T) / repeat_count

  Determine time to execute statement (or block) of Python code.

  Here global_dict is the globals dict used for exec, Tmax is the max
  time to spend in pytime_statement(), in sec, and repeat_count is the
  number of times to paste stmt into the inner timing loop (this is
  automatically set to 1 if stmt takes too long).
  
recipes/Python/440657_Determine_functiexecutitime_Pythonic/recipe-440657.py