Today I was looking for a quick and dirty way to profile a method of a class. I was thinking that cProfile module had a decorator for this but I was wrong so I decided to write one based on hotshot. Would it be worth for inclusion?
#!/usr/bin/env python import hotshot import hotshot.stats import tempfile import pstats def profile(sort='cumulative', lines=30, strip_dirs=False): """A decorator which profiles a callable. Example usage: >>> @profile() ... def factorial(n): ... n = abs(int(n)) ... if n < 1: ... n = 1 ... x = 1 ... for i in range(1, n+1): ... x = i * x ... return x ... >>> factorial(5) 1 function calls in 0.000 CPU seconds Ordered by: internal time, call count ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 profiler.py:60(factorial) 0 0.000 0.000 profile:0(profiler) 120 >>> """ def outer(fun): def inner(*args, **kwargs): file = tempfile.NamedTemporaryFile() prof = hotshot.Profile(file.name) try: ret = prof.runcall(fun, *args, **kwargs) finally: prof.close() stats = hotshot.stats.load(file.name) if strip_dirs: stats.strip_dirs() if isinstance(sort, tuple): stats.sort_stats(*sort) else: stats.sort_stats(sort) stats.print_stats(lines) return ret return inner return outer _______________________________________________ Python-Dev mailing list Python-Dev@python.org http://mail.python.org/mailman/listinfo/python-dev Unsubscribe: http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com