Skip to content

Instantly share code, notes, and snippets.

@nicholasmireles
Created August 19, 2022 22:22
Show Gist options
  • Save nicholasmireles/4fbcf22f8cb43337192ba8448a0b1b04 to your computer and use it in GitHub Desktop.
Save nicholasmireles/4fbcf22f8cb43337192ba8448a0b1b04 to your computer and use it in GitHub Desktop.
A one-line profiler: Simply add "import profiler" to your script
import cProfile
import inspect
import sys
# Ensure that we aren't being run directly
if __name__ != "__main__":
caller = None
# Look for the first actual .py filename
for frame in inspect.stack()[1:]:
if not frame.filename.startswith("<"):
caller = frame.filename
break
# Set some important global variables
globals = {
"__file__": caller,
"__name__": "__main__",
"__package__": None,
"__cached__": None,
}
# Read the script that imported us into memory
with open(caller, "r") as tmp:
# Remove the line that imported us to prevent a loop
caller_rewritten = tmp.read().replace("import profiler", "")
code = compile(caller_rewritten, caller, "exec")
try:
cProfile.runctx(code, globals, None)
sys.exit(0)
except BrokenPipeError as exc:
sys.stdout = None
sys.exit(exc.errno)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment