Skip to content

Instantly share code, notes, and snippets.

@ethanal
Created June 25, 2015 02:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ethanal/d8e0a1288cb560846818 to your computer and use it in GitHub Desktop.
Save ethanal/d8e0a1288cb560846818 to your computer and use it in GitHub Desktop.
Simple python profiler
import functools
from time import time
from .text_styles import *
class ProfileItem(object):
def __init__(self, name, elapsed, stats):
self.name = name
self.elapsed = elapsed
self.stats = stats
def __str__(self):
sorted_stats = sorted(self.stats.items(), key=lambda t: t[0])
stats_string = "\n ".join(map(lambda kv: "{}: {}".format(kv[0].title(), kv[1]), sorted_stats))
if stats_string != "":
stats_string = "\n " + stats_string
return "{} {} seconds{}".format(cyan(bold(self.name + ":")),
self.elapsed,
stats_string)
class Profiler(object):
def __init__(self, defer_printing=False):
self.defer_printing = defer_printing
self.print_queue = []
def _handle_print(self, print_item):
line = str(print_item)
if self.defer_printing:
print(green(">>> Finished {}".format(print_item.name)))
self.print_queue.append(line)
else:
print(line)
def flush_print_queue(self):
if self.defer_printing:
print(underlined(magenta("\nProfile")))
for line in self.print_queue:
print(line)
print()
self.print_queue = []
def profile(self, name):
def wrapper(func):
@functools.wraps(func)
def wrapped(*args, **kwargs):
ret = None
start_time = time()
profiler_stats = {}
try:
ret = func(*args, profiler_stats=profiler_stats, **kwargs)
except TypeError as e:
if "profiler_stats" in str(e):
ret = func(*args, **kwargs)
else:
raise
end_time = time()
elapsed = end_time - start_time
profile_item = ProfileItem(name, elapsed, profiler_stats)
self._handle_print(profile_item)
return ret
return wrapped
return wrapper
@ethanal
Copy link
Author

ethanal commented Jun 25, 2015

Requires text_styles.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment