Skip to content

Instantly share code, notes, and snippets.

@mynameisfiber
Created January 13, 2016 22:12
Show Gist options
  • Select an option

  • Save mynameisfiber/b0deb6eedaf8fe410960 to your computer and use it in GitHub Desktop.

Select an option

Save mynameisfiber/b0deb6eedaf8fe410960 to your computer and use it in GitHub Desktop.
Times code within a contextmanager with useful stack information in output
import time
import contextlib
import inspect
_DEBUG = False
@contextlib.contextmanager
def Timer(name, debug=_DEBUG):
if not debug:
yield
return
start = time.time()
yield
end = time.time()
path = [name]
for frame in inspect.stack()[2:]:
if frame[3] == "<module>":
break
path.append(frame[3])
path_str = ".".join(reversed(path))
print("Timer: {}: {:0.5f}s".format(path_str, end-start))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment