_timing.py 2.3 KB

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