_timing.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # fmt: off
  2. # flake8: noqa
  3. # pyre-unsafe
  4. import inspect
  5. from functools import wraps
  6. from time import perf_counter
  7. DO_TIMING = False
  8. DISPLAY_LESS_PROGRESS = False
  9. timer_dict = {}
  10. counter = 0
  11. def time(f):
  12. @wraps(f)
  13. def wrap(*args, **kw):
  14. if DO_TIMING:
  15. # Run function with timing
  16. ts = perf_counter()
  17. result = f(*args, **kw)
  18. te = perf_counter()
  19. tt = te - ts
  20. # Get function name
  21. arg_names = inspect.getfullargspec(f)[0]
  22. if arg_names[0] == "self" and DISPLAY_LESS_PROGRESS:
  23. return result
  24. elif arg_names[0] == "self":
  25. method_name = type(args[0]).__name__ + "." + f.__name__
  26. else:
  27. method_name = f.__name__
  28. # Record accumulative time in each function for analysis
  29. if method_name in timer_dict.keys():
  30. timer_dict[method_name] += tt
  31. else:
  32. timer_dict[method_name] = tt
  33. # If code is finished, display timing summary
  34. if method_name == "Evaluator.evaluate":
  35. print("")
  36. print("Timing analysis:")
  37. for key, value in timer_dict.items():
  38. print("%-70s %2.4f sec" % (key, value))
  39. else:
  40. # Get function argument values for printing special arguments of interest
  41. arg_titles = ["tracker", "seq", "cls"]
  42. arg_vals = []
  43. for i, a in enumerate(arg_names):
  44. if a in arg_titles:
  45. arg_vals.append(args[i])
  46. arg_text = "(" + ", ".join(arg_vals) + ")"
  47. # Display methods and functions with different indentation.
  48. if arg_names[0] == "self":
  49. print("%-74s %2.4f sec" % (" " * 4 + method_name + arg_text, tt))
  50. elif arg_names[0] == "test":
  51. pass
  52. else:
  53. global counter
  54. counter += 1
  55. print("%i %-70s %2.4f sec" % (counter, method_name + arg_text, tt))
  56. return result
  57. else:
  58. # If config["TIME_PROGRESS"] is false, or config["USE_PARALLEL"] is true, run functions normally without timing.
  59. return f(*args, **kw)
  60. return wrap