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 799B

123456789101112131415161718192021222324252627282930
  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 https://speakerdeck.com/rwarren/a-brief-intro-to-profiling-in-python
  8. """
  9. def profiled_fn(*args, **kwargs):
  10. filepath = "/tmp/%s.profile" % fn.__name__
  11. prof = cProfile.Profile()
  12. start = time.time()
  13. result = prof.runcall(fn, *args, **kwargs)
  14. duration = time.time() - start
  15. print "Function ran in %.6f seconds - output written to %s" % (
  16. duration, filepath)
  17. prof.dump_stats(filepath)
  18. print "Printing stats"
  19. stats = pstats.Stats(filepath)
  20. stats.sort_stats('cumulative')
  21. stats.print_stats()
  22. return result
  23. return profiled_fn