图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
1.9 KiB

  1. """Simple tools for timing functions' execution, when IPython is not available. """
  2. import timeit
  3. import math
  4. _scales = [1e0, 1e3, 1e6, 1e9]
  5. _units = ['s', 'ms', '\N{GREEK SMALL LETTER MU}s', 'ns']
  6. def timed(func, setup="pass", limit=None):
  7. """Adaptively measure execution time of a function. """
  8. timer = timeit.Timer(func, setup=setup)
  9. repeat, number = 3, 1
  10. for i in range(1, 10):
  11. if timer.timeit(number) >= 0.2:
  12. break
  13. elif limit is not None and number >= limit:
  14. break
  15. else:
  16. number *= 10
  17. time = min(timer.repeat(repeat, number)) / number
  18. if time > 0.0:
  19. order = min(-int(math.floor(math.log10(time)) // 3), 3)
  20. else:
  21. order = 3
  22. return (number, time, time*_scales[order], _units[order])
  23. # Code for doing inline timings of recursive algorithms.
  24. def __do_timings():
  25. import os
  26. res = os.getenv('SYMPY_TIMINGS', '')
  27. res = [x.strip() for x in res.split(',')]
  28. return set(res)
  29. _do_timings = __do_timings()
  30. _timestack = None
  31. def _print_timestack(stack, level=1):
  32. print('-'*level, '%.2f %s%s' % (stack[2], stack[0], stack[3]))
  33. for s in stack[1]:
  34. _print_timestack(s, level + 1)
  35. def timethis(name):
  36. def decorator(func):
  37. global _do_timings
  38. if name not in _do_timings:
  39. return func
  40. def wrapper(*args, **kwargs):
  41. from time import time
  42. global _timestack
  43. oldtimestack = _timestack
  44. _timestack = [func.func_name, [], 0, args]
  45. t1 = time()
  46. r = func(*args, **kwargs)
  47. t2 = time()
  48. _timestack[2] = t2 - t1
  49. if oldtimestack is not None:
  50. oldtimestack[1].append(_timestack)
  51. _timestack = oldtimestack
  52. else:
  53. _print_timestack(_timestack)
  54. _timestack = None
  55. return r
  56. return wrapper
  57. return decorator