def pytime(f, args=(), kwargs={}, Tmax=2.0):
  """
  Calls f many times to determine the average time to execute f.

  Tmax is the maximum time to spend in pytime(), in seconds.
  """
  count = 1
  while True:
    start = clock()
    if args == () and kwargs == {}:
      for i in xrange(count):
        f()
    elif kwargs == {}:
      for i in xrange(count):
        f(*args)
    else:
      for i in xrange(count):
        f(*args, **kwargs)
    T = clock() - start
    if T >= Tmax/4.0: break
    count *= 2
  return T / count

  Calls f many times to determine the average time to execute f.

  Tmax is the maximum time to spend in pytime(), in seconds.
  
recipes/Python/440657_Determine_functiexecutitime_Pythonic/recipe-440657.py