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.

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