Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

✨ Generate event specific reports #32

Merged
merged 23 commits into from
Sep 16, 2023
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ max-complexity = 20

[tool.ruff.per-file-ignores]
"sphinx_performance/projects/basic/performance.py" = ["INP001"] # template dir
"sphinx_performance/projects/events/performance.py" = ["INP001"] # template dir
"sphinx_performance/projects/needs/performance.py" = ["INP001"] # template dir
"sphinx_performance/projects/theme/performance.py" = ["INP001"] # template dir

Expand Down
23 changes: 19 additions & 4 deletions sphinx_performance/analysis.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Executes several performance tests."""
import json
import os.path
import subprocess
import sys
Expand All @@ -8,11 +9,12 @@
from pathlib import Path

import click
from pyinstrument.renderers import HTMLRenderer
from pyinstrument.renderers import JSONRenderer

from sphinx_performance.call import Call
from sphinx_performance.config import MEMORY_HTML, MEMORY_PROFILE, RUNTIME_PROFILE
from sphinx_performance.projectenv import ProjectEnv
from sphinx_performance.renderers.html import HTMLRendererFromJson
from sphinx_performance.utils import console


Expand Down Expand Up @@ -251,16 +253,29 @@ def cli_analysis(
show_all = False
processor_options["filter_threshold"] = tree_filter

html_data = HTMLRenderer(
json_str = JSONRenderer(
show_all=show_all,
processor_options=processor_options,
).render(
all_profile,
)
with Path.open("pyinstrument_profile.html", "w") as profile_html:
profile_html.write(html_data)
html_data = HTMLRendererFromJson(
show_all=show_all,
processor_options=processor_options,
).render(
json_str,
)
with Path.open(Path("pyinstrument_profile.html"), "w") as events_json_file:
ubmarco marked this conversation as resolved.
Show resolved Hide resolved
events_json_file.write(html_data)
webbrowser.open_new_tab("pyinstrument_profile.html")

from sphinx_performance.sphinx_events import aggregate_event_runtime

json_obj = json.loads(json_str)
aggregate_json = aggregate_event_runtime(json_obj)
with Path.open(Path("pyinstrument_sphinx_events.json"), "w") as events_json_file:
json.dump(aggregate_json, events_json_file, indent=2, sort_keys=True)

if flamegraph:
if runtime:
console.print("\nStarting snakeviz servers\n")
Expand Down
1 change: 1 addition & 0 deletions sphinx_performance/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

PROJECTS = {
"basic": Path(Path(__file__).parent) / "projects" / "basic",
"events": Path(Path(__file__).parent) / "projects" / "events",
"needs": Path(Path(__file__).parent) / "projects" / "needs",
"theme": Path(Path(__file__).parent) / "projects" / "theme",
}
Expand Down
1 change: 1 addition & 0 deletions sphinx_performance/performance.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

PROJECTS = {
"basic": Path(Path(__file__).parent) / "projects" / "basic",
"events": Path(Path(__file__).parent) / "projects" / "events",
"needs": Path(Path(__file__).parent) / "projects" / "needs",
"theme": Path(Path(__file__).parent) / "projects" / "theme",
}
Expand Down
34 changes: 21 additions & 13 deletions sphinx_performance/projectenv.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@
import webbrowser
from contextlib import suppress
from pathlib import Path
from unittest.mock import patch

import memray
from jinja2 import Template
from pyinstrument import Profiler
from sphinx.application import Sphinx

from sphinx_performance.config import MEMORY_PROFILE, MEMRAY_PORT
from sphinx_performance.sphinx_events import EventManager
from sphinx_performance.utils import console

NEED_CONFIG_DEFAULT = ["pages", "folders", "depth"]
Expand Down Expand Up @@ -501,22 +503,28 @@ def build_internal(
self.build_config["keep"] = True

start_time = time.time()
app = Sphinx(
srcdir=self.target_path,
confdir=self.target_path,
outdir=self.target_build_path,
doctreedir=self.target_build_path,
buildername=str(self.build_config["builder"]),
parallel=int(self.build_config["parallel"]),
)

def init_sphinx_and_start():
with patch("sphinx.application.EventManager", EventManager):
app = Sphinx(
srcdir=self.target_path,
confdir=self.target_path,
outdir=self.target_build_path,
doctreedir=self.target_build_path,
buildername=str(self.build_config["builder"]),
parallel=int(self.build_config["parallel"]),
)
return app.build()

if use_runtime:
with cProfile.Profile() as profile:
app.build()
init_sphinx_and_start()

status_code = 0
if use_memray:
memray_file = memray.FileDestination(path=MEMORY_PROFILE, overwrite=True)
with memray.Tracker(destination=memray_file):
app.build()
status_code = init_sphinx_and_start()

if use_memray_live:
console.print(
Expand All @@ -526,19 +534,19 @@ def build_internal(
)
memray_port = memray.SocketDestination(server_port=MEMRAY_PORT)
with memray.Tracker(destination=memray_port):
app.build()
status_code = init_sphinx_and_start()

if use_pyinstrument:
profiler = Profiler()
import inspect

profiler.start(caller_frame=inspect.currentframe().f_back)
app.build()
status_code = init_sphinx_and_start()
profile = profiler.stop() # Returns a pyinstrument session

end_time = time.time()
build_time = end_time - start_time
return app.statuscode, build_time, profile
return status_code, build_time, profile

def post_processing(self):
if self.build_config["browser"]:
Expand Down
1 change: 1 addition & 0 deletions sphinx_performance/projects/events/_static/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
empty...
152 changes: 152 additions & 0 deletions sphinx_performance/projects/events/conf.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
#
# needs test docs documentation build configuration file, created by
# sphinx-quickstart on Tue Mar 28 11:37:14 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys

sys.path.insert(0, os.path.abspath("../../sphinxcontrib"))
sys.path.insert(0, os.path.abspath("."))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.


extensions = [
"event_extension",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
source_suffix = ".rst"

# The master toctree document.
master_doc = "index"

# General information about the project.
project = "needs test docs"
copyright = "team testing"
author = "team testing"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = "1.0"
# The full version, including alpha/beta/rc tags.
release = "1.0"

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "sphinx"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "alabaster"

# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ["_static"]

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "needstestdocsdoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# The font size ('10pt', '11pt' or '12pt').
#
# Additional stuff for the LaTeX preamble.
#
# Latex figure (float) alignment
#
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(
master_doc,
"needstestdocs.tex",
"needs test docs Documentation",
"team useblocks",
"manual",
),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, "needstestdocs", "needs test docs Documentation", [author], 1)
]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(
master_doc,
"needstestdocs",
"needs test docs Documentation",
author,
"needstestdocs",
"One line description of project.",
"Miscellaneous",
),
]
59 changes: 59 additions & 0 deletions sphinx_performance/projects/events/event_extension/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""
Extension that connects to all Sphinx events and sleeps in those.

Can be used to test the debuggers.
"""
from __future__ import annotations

from typing import TYPE_CHECKING, Any

if TYPE_CHECKING:
from sphinx.application import Sphinx


def wait_generic(event, ret_val=None):
"""Wait for a short time so debuggers see the event fired."""
# generate event specific wait function name
event_identifier = event.replace("-", "_")
func_name = f"wait_{event_identifier}"
exec( # noqa: S102 exec-builtin - wanted here
f"""def {func_name}(*args, **kwargs):
from time import sleep
sleep(.1)
# print("func '{func_name}' invoked for event '{event}'")
return {ret_val}""",
)
return locals().get(func_name)


def setup(app: Sphinx) -> dict[str, Any]:
"""Entry point for Sphinx."""
# Make connections to events
events = [
["builder-inited"], # invoked
["config-inited"], # invoked
["env-get-outdated", []], # invoked
["env-purge-doc"], # invoked
["env-before-read-docs"], # invoked
["source-read"], # invoked
["object-description-transform"],
["doctree-read"], # invoked
["missing-reference"], # invoked
["warn-missing-reference"], # invoked
["doctree-resolved"], # invoked
["env-merge-info"], # invoked
["env-updated"], # invoked
["env-check-consistency"], # invoked
["html-collect-pages", []], # invoked
["html-page-context"], # invoked
["linkcheck-process-uri"],
["build-finished"], # invoked
]
for event in events:
app.connect(event[0], wait_generic(*event))

return {
"version": "0.1.0",
"parallel_read_safe": True,
"parallel_write_safe": True,
}
28 changes: 28 additions & 0 deletions sphinx_performance/projects/events/index.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{{ title}}
{{ "=" * title|length }}

Config
------
:pages: {{pages}}
:dummies: {{dummies}}
:keep: {{keep}}
:browser: {{browser}}
:debug: {{debug}}

Content
-------
.. contents::

.. toctree::

{%- for page in range(pages) %}
page_{{page}}
{%- endfor -%}

{%- if has_folders %}
{%- for folder in range(folders) %}
folder_{{folder}}/index
{%- endfor -%}
{% endif %}

This is a :ref:`missing` reference.
Loading
Loading