| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import asyncio |
| 4 |
import html |
| 5 |
import threading |
| 6 |
import urllib.parse |
| 7 |
from ast import parse |
| 8 |
from textwrap import dedent |
| 9 |
|
| 10 |
import IPython |
| 11 |
from IPython import get_ipython |
| 12 |
from IPython.core.magic import Magics, line_cell_magic, magics_class, no_var_expand |
| 13 |
from IPython.core.magic_arguments import argument, magic_arguments, parse_argstring |
| 14 |
from IPython.display import IFrame, display |
| 15 |
|
| 16 |
from pyinstrument import Profiler, renderers |
| 17 |
from pyinstrument.__main__ import compute_render_options |
| 18 |
from pyinstrument.frame import Frame |
| 19 |
from pyinstrument.frame_ops import delete_frame_from_tree |
| 20 |
from pyinstrument.processors import ProcessorOptions |
| 21 |
from pyinstrument.renderers.console import ConsoleRenderer |
| 22 |
from pyinstrument.renderers.html import HTMLRenderer |
| 23 |
|
| 24 |
_active_profiler = None |
| 25 |
|
| 26 |
_ASYNCIO_HTML_WARNING = """ |
| 27 |
To enable asyncio mode, use <pre>%%pyinstrument --async_mode=enabled</pre><br> |
| 28 |
Note that due to IPython limitations this will run in a separate thread! |
| 29 |
""".strip() |
| 30 |
_ASYNCIO_TEXT_WARNING = ( |
| 31 |
_ASYNCIO_HTML_WARNING.replace("<pre>", "`").replace("</pre>", "`").replace("<br>", "\n") |
| 32 |
) |
| 33 |
|
| 34 |
|
| 35 |
def _get_active_profiler(): |
| 36 |
""" |
| 37 |
Allows the code inserted into the cell to access the pyinstrument Profiler |
| 38 |
instance, to start/stop it. |
| 39 |
""" |
| 40 |
return _active_profiler |
| 41 |
|
| 42 |
|
| 43 |
class InterruptSilently(Exception): |
| 44 |
"""Exception used to interrupt execution without showing traceback""" |
| 45 |
|
| 46 |
|
| 47 |
@magics_class |
| 48 |
class PyinstrumentMagic(Magics): |
| 49 |
def __init__(self, shell): |
| 50 |
super().__init__(shell) |
| 51 |
self._transformer = None |
| 52 |
|
| 53 |
def recreate_transformer(self, target_description: str): |
| 54 |
if IPython.version_info < (8, 15): |
| 55 |
from ._utils import PrePostAstTransformer |
| 56 |
|
| 57 |
|
| 58 |
pre = parse( |
| 59 |
dedent( |
| 60 |
f""" |
| 61 |
from pyinstrument.magic.magic import _get_active_profiler |
| 62 |
_get_active_profiler().start(target_description={target_description!r}) |
| 63 |
""" |
| 64 |
) |
| 65 |
) |
| 66 |
post = parse("\n_get_active_profiler().stop()") |
| 67 |
self._transformer = PrePostAstTransformer(pre, post) |
| 68 |
else: |
| 69 |
from IPython.core.magics.ast_mod import ReplaceCodeTransformer |
| 70 |
|
| 71 |
self._transformer = ReplaceCodeTransformer.from_string( |
| 72 |
dedent( |
| 73 |
f""" |
| 74 |
from pyinstrument.magic.magic import _get_active_profiler as ___get_prof |
| 75 |
___get_prof().start(target_description={target_description!r}) |
| 76 |
try: |
| 77 |
__code__ |
| 78 |
finally: |
| 79 |
___get_prof().stop() |
| 80 |
__ret__ |
| 81 |
""" |
| 82 |
) |
| 83 |
) |
| 84 |
|
| 85 |
@magic_arguments() |
| 86 |
@argument( |
| 87 |
"-p", |
| 88 |
"--render-option", |
| 89 |
dest="render_options", |
| 90 |
action="append", |
| 91 |
metavar="RENDER_OPTION", |
| 92 |
type=str, |
| 93 |
help=( |
| 94 |
"options to pass to the renderer, in the format 'flag_name' or 'option_name=option_value'. " |
| 95 |
"For example, to set the option 'time', pass '-p time=percent_of_total'. To pass multiple " |
| 96 |
"options, use the -p option multiple times. You can set processor options using dot-syntax, " |
| 97 |
"like '-p processor_options.filter_threshold=0'. option_value is parsed as a JSON value or " |
| 98 |
"a string." |
| 99 |
), |
| 100 |
) |
| 101 |
@argument( |
| 102 |
"--show-regex", |
| 103 |
dest="show_regex", |
| 104 |
action="store", |
| 105 |
metavar="REGEX", |
| 106 |
help=( |
| 107 |
"regex matching the file paths whose frames to always show. " |
| 108 |
"Useful if --show doesn't give enough control." |
| 109 |
), |
| 110 |
) |
| 111 |
@argument( |
| 112 |
"--show", |
| 113 |
dest="show_fnmatch", |
| 114 |
action="store", |
| 115 |
metavar="EXPR", |
| 116 |
help=( |
| 117 |
"glob-style pattern matching the file paths whose frames to " |
| 118 |
"show, regardless of --hide or --hide-regex. For example, use " |
| 119 |
"--show '*/<library>/*' to show frames within a library that " |
| 120 |
"would otherwise be hidden." |
| 121 |
), |
| 122 |
) |
| 123 |
@argument( |
| 124 |
"--interval", |
| 125 |
type=float, |
| 126 |
default=0.001, |
| 127 |
help="The minimum time, in seconds, between each stack sample. See: https://pyinstrument.readthedocs.io/en/stable/reference.html#pyinstrument.Profiler.interval", |
| 128 |
) |
| 129 |
@argument( |
| 130 |
"--show-all", |
| 131 |
action="store_true", |
| 132 |
help="SHow all frames, including root frames with no time, and Internal IPython frames.", |
| 133 |
) |
| 134 |
@argument( |
| 135 |
"--async_mode", |
| 136 |
default="disabled", |
| 137 |
help="Configures how this Profiler tracks time in a program that uses async/await. See: https://pyinstrument.readthedocs.io/en/stable/reference.html#pyinstrument.Profiler.async_mode", |
| 138 |
) |
| 139 |
@argument( |
| 140 |
"--height", |
| 141 |
"-h", |
| 142 |
default=400, |
| 143 |
help="Output height", |
| 144 |
) |
| 145 |
@argument( |
| 146 |
"--timeline", |
| 147 |
type=bool, |
| 148 |
default=False, |
| 149 |
help="Show output timeline view", |
| 150 |
) |
| 151 |
@argument( |
| 152 |
"code", |
| 153 |
type=str, |
| 154 |
nargs="*", |
| 155 |
help="When used as a line magic, the code to profile", |
| 156 |
) |
| 157 |
@argument( |
| 158 |
"--hide", |
| 159 |
dest="hide_fnmatch", |
| 160 |
action="store", |
| 161 |
metavar="EXPR", |
| 162 |
help=( |
| 163 |
"glob-style pattern matching the file paths whose frames to hide. Defaults to " |
| 164 |
"hiding non-application code" |
| 165 |
), |
| 166 |
) |
| 167 |
@argument( |
| 168 |
"--hide-regex", |
| 169 |
dest="hide_regex", |
| 170 |
action="store", |
| 171 |
metavar="REGEX", |
| 172 |
help=( |
| 173 |
"regex matching the file paths whose frames to hide. Useful if --hide doesn't give " |
| 174 |
"enough control." |
| 175 |
), |
| 176 |
) |
| 177 |
@no_var_expand |
| 178 |
@line_cell_magic |
| 179 |
def pyinstrument(self, line, cell=None): |
| 180 |
""" |
| 181 |
Run a cell with the pyinstrument statistical profiler. |
| 182 |
|
| 183 |
Converts the line/cell's AST to something like: |
| 184 |
try: |
| 185 |
profiler.start() |
| 186 |
run_code |
| 187 |
finally: |
| 188 |
profiler.stop() |
| 189 |
profiler.output_html() |
| 190 |
""" |
| 191 |
global _active_profiler |
| 192 |
args = parse_argstring(self.pyinstrument, line) |
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
args.unicode = True |
| 197 |
args.color = True |
| 198 |
|
| 199 |
ip = get_ipython() |
| 200 |
|
| 201 |
if not ip: |
| 202 |
raise RuntimeError("couldn't get ipython shell instance") |
| 203 |
|
| 204 |
if cell: |
| 205 |
target_description = f"Cell [{ip.execution_count}]" |
| 206 |
else: |
| 207 |
target_description = f"Line in cell [{ip.execution_count}]" |
| 208 |
code = cell or line |
| 209 |
|
| 210 |
if not code: |
| 211 |
return |
| 212 |
|
| 213 |
|
| 214 |
if _active_profiler and _active_profiler.is_running: |
| 215 |
_active_profiler.stop() |
| 216 |
if self._transformer in ip.ast_transformers: |
| 217 |
ip.ast_transformers.remove(self._transformer) |
| 218 |
|
| 219 |
_active_profiler = Profiler(interval=args.interval, async_mode=args.async_mode) |
| 220 |
self.recreate_transformer(target_description=target_description) |
| 221 |
ip.ast_transformers.append(self._transformer) |
| 222 |
if args.async_mode == "disabled": |
| 223 |
cell_result = ip.run_cell(code) |
| 224 |
else: |
| 225 |
cell_result = self.run_cell_async(ip, code) |
| 226 |
mangled_keys = [k for k in ip.user_ns.keys() if "-" in k] |
| 227 |
for k in mangled_keys: |
| 228 |
del ip.user_ns[k] |
| 229 |
ip.ast_transformers.remove(self._transformer) |
| 230 |
|
| 231 |
if ( |
| 232 |
args.async_mode == "disabled" |
| 233 |
and cell_result.error_in_exec |
| 234 |
and isinstance(cell_result.error_in_exec, RuntimeError) |
| 235 |
and "event loop is already running" in str(cell_result.error_in_exec) |
| 236 |
): |
| 237 |
|
| 238 |
|
| 239 |
display( |
| 240 |
{ |
| 241 |
"text/plain": _ASYNCIO_TEXT_WARNING, |
| 242 |
"text/html": _ASYNCIO_HTML_WARNING, |
| 243 |
}, |
| 244 |
raw=True, |
| 245 |
) |
| 246 |
return |
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
if isinstance(cell_result.error_in_exec, KeyboardInterrupt): |
| 251 |
|
| 252 |
|
| 253 |
old_custom_tb = ip.CustomTB |
| 254 |
old_custom_exceptions = ip.custom_exceptions |
| 255 |
|
| 256 |
def _silent_exception_handler(self, etype, value, tb, tb_offset=None): |
| 257 |
|
| 258 |
ip.CustomTB = old_custom_tb |
| 259 |
ip.custom_exceptions = old_custom_exceptions |
| 260 |
|
| 261 |
|
| 262 |
|
| 263 |
ip.set_custom_exc((InterruptSilently,), _silent_exception_handler) |
| 264 |
raise InterruptSilently() |
| 265 |
|
| 266 |
html_config = compute_render_options( |
| 267 |
args, renderer_class=HTMLRenderer, unicode_support=True, color_support=True |
| 268 |
) |
| 269 |
|
| 270 |
text_config = compute_render_options( |
| 271 |
args, renderer_class=HTMLRenderer, unicode_support=True, color_support=True |
| 272 |
) |
| 273 |
|
| 274 |
html_renderer = renderers.HTMLRenderer(show_all=args.show_all, timeline=args.timeline) |
| 275 |
html_renderer.preprocessors.append(strip_ipython_frames_processor) |
| 276 |
html_str = _active_profiler.output(html_renderer) |
| 277 |
as_iframe = IFrame( |
| 278 |
src="data:text/html, Loading…", |
| 279 |
width="100%", |
| 280 |
height=args.height, |
| 281 |
extras=['style="resize: vertical"', f'srcdoc="{html.escape(html_str)}"'], |
| 282 |
) |
| 283 |
|
| 284 |
text_renderer = renderers.ConsoleRenderer(**text_config) |
| 285 |
text_renderer.processors.append(strip_ipython_frames_processor) |
| 286 |
|
| 287 |
as_text = _active_profiler.output(text_renderer) |
| 288 |
|
| 289 |
display({"text/html": as_iframe._repr_html_(), "text/plain": as_text}, raw=True) |
| 290 |
|
| 291 |
assert not _active_profiler.is_running |
| 292 |
_active_profiler = None |
| 293 |
|
| 294 |
def run_cell_async(self, ip, code): |
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
old_loop = asyncio.get_event_loop() |
| 302 |
loop = asyncio.new_event_loop() |
| 303 |
try: |
| 304 |
threading.Thread(target=loop.run_forever).start() |
| 305 |
asyncio.set_event_loop(loop) |
| 306 |
coro = ip.run_cell_async(code) |
| 307 |
future = asyncio.run_coroutine_threadsafe(coro, loop) |
| 308 |
return future.result() |
| 309 |
finally: |
| 310 |
loop.call_soon_threadsafe(loop.stop) |
| 311 |
asyncio.set_event_loop(old_loop) |
| 312 |
|
| 313 |
|
| 314 |
IPYTHON_INTERNAL_FILES = ( |
| 315 |
"IPython/core/interactiveshell.py", |
| 316 |
"IPython/terminal/interactiveshell.py", |
| 317 |
"IPython/core/async_helpers.py", |
| 318 |
"IPython/terminal/ipapp.py", |
| 319 |
"traitlets/config/application.py", |
| 320 |
"ipython/IPython/__init__.py", |
| 321 |
"ipykernel/zmqshell", |
| 322 |
"pyinstrument/magic/magic.py", |
| 323 |
) |
| 324 |
|
| 325 |
|
| 326 |
def strip_ipython_frames_processor(frame: Frame | None, options: ProcessorOptions) -> Frame | None: |
| 327 |
""" |
| 328 |
A processor function that removes internal IPython nodes. |
| 329 |
""" |
| 330 |
if frame is None: |
| 331 |
return None |
| 332 |
|
| 333 |
for child in frame.children: |
| 334 |
strip_ipython_frames_processor(child, options=options) |
| 335 |
|
| 336 |
if child.file_path is not None and any( |
| 337 |
f in child.file_path for f in IPYTHON_INTERNAL_FILES |
| 338 |
): |
| 339 |
delete_frame_from_tree(child, replace_with="children") |
| 340 |
break |
| 341 |
|
| 342 |
return frame |