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.

decorators.py 881B

123456789101112131415161718192021222324252627282930313233
  1. from __future__ import print_function
  2. from __future__ import print_function
  3. import cProfile
  4. import pstats
  5. import time
  6. def profile(fn):
  7. """
  8. Profile the decorated function, storing the profile output in /tmp
  9. Inspired by
  10. https://speakerdeck.com/rwarren/a-brief-intro-to-profiling-in-python
  11. """
  12. def profiled_fn(*args, **kwargs):
  13. filepath = "/tmp/%s.profile" % fn.__name__
  14. prof = cProfile.Profile()
  15. start = time.time()
  16. result = prof.runcall(fn, *args, **kwargs)
  17. duration = time.time() - start
  18. print("Function ran in %.6f seconds - output written to %s" % (
  19. duration, filepath))
  20. prof.dump_stats(filepath)
  21. print("Printing stats")
  22. stats = pstats.Stats(filepath)
  23. stats.sort_stats('cumulative')
  24. stats.print_stats()
  25. return result
  26. return profiled_fn