Created
January 13, 2016 22:12
-
-
Save mynameisfiber/b0deb6eedaf8fe410960 to your computer and use it in GitHub Desktop.
Times code within a contextmanager with useful stack information in output
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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