{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "56775d89",
   "metadata": {},
   "source": [
    "# Part 1. How to measure the running time of a program\n",
    "\n",
    "In Python the same result can be computed in many ways, and the running times of different programs\n",
    "can differ by several orders of magnitude. Before we start speeding programs up, we must be able to\n",
    "measure time fairly: compare only programs that compute the same thing, and do it so that the result\n",
    "does not depend on chance. The guiding example of this part comes from the instructor’s study of\n",
    "Python performance. It consists of two short programs that sum $i+j$ over all pairs $0\\le i,j<100$.\n",
    "We checked a similar sum in Lecture 1\n",
    "({doc}`§1.2 <../wyklady/w01_2_python_matematyka>`), when we compared the sum $1+2+\\dots+n$\n",
    "with Gauss’s formula.\n",
    "\n",
    "## Two programs, the same result\n",
    "\n",
    "The first program adds up the terms in two nested `for` loops. The second passes a *generator\n",
    "expression*, which yields the successive terms, to the function `sum`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67b72328",
   "metadata": {},
   "outputs": [],
   "source": [
    "suma = 0\n",
    "for i in range(100):\n",
    "    for j in range(100):\n",
    "        suma += i + j\n",
    "print(suma)\n",
    "\n",
    "print(sum(i + j for i in range(100) for j in range(100)))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c090b52b",
   "metadata": {},
   "source": [
    "Both programs print the same number, and this is no coincidence. In the sum over all pairs, each\n",
    "value of $i$ occurs $n$ times, and so does each value of $j$, so\n",
    "\n",
    "$$\n",
    "S(n)=\\sum_{i=0}^{n-1}\\sum_{j=0}^{n-1}(i+j)=2n\\sum_{i=0}^{n-1}i=2n\\cdot\\frac{n(n-1)}{2}=n^2(n-1).\n",
    "$$\n",
    "\n",
    "SymPy, which can sum symbolically, will carry out the same computation:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d985d204",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sympy as sp\n",
    "\n",
    "i, j, n = sp.symbols(\"i j n\", integer=True, nonnegative=True)\n",
    "S = sp.summation(sp.summation(i + j, (j, 0, n - 1)), (i, 0, n - 1))\n",
    "print(\"S(n) =\", sp.factor(S), \"  S(100) =\", S.subs(n, 100))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "83c62656",
   "metadata": {},
   "source": [
    "The formula $S(n)=n^2(n-1)$ is a **contract**: it says what every variant of the program must\n",
    "compute. Before comparing times, we will always check that the variants give the same result,\n",
    "because otherwise we would be comparing different tasks. The formula itself is also a variant of the\n",
    "program, and the fastest one at that, but we will get to it at the end of this part.\n",
    "\n",
    "## One measurement is not enough\n",
    "\n",
    "The simplest clock in Python is `time.perf_counter()`: it returns the number of seconds elapsed since\n",
    "a certain moment and is good only for subtracting two readings. Let us wrap the first program in\n",
    "a function and measure a call to it five times."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7e7f3747",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "\n",
    "def suma_petla(n):\n",
    "    s = 0\n",
    "    for i in range(n):\n",
    "        for j in range(n):\n",
    "            s += i + j\n",
    "    return s\n",
    "\n",
    "\n",
    "for _ in range(5):\n",
    "    start = time.perf_counter()\n",
    "    suma_petla(100)\n",
    "    print(f\"{(time.perf_counter() - start) * 1e6:.1f} µs\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93d8dcb2",
   "metadata": {},
   "source": [
    "The results differ, although the program computes the same thing every time. The time is affected\n",
    "by other programs running at the same moment, by the state of the processor’s cache, and by changes\n",
    "in its clock frequency. The first call is often slower than the following ones, because since\n",
    "version 3.11 the CPython interpreter adapts bytecode instructions to the data types it sees (the\n",
    "*specializing adaptive interpreter*, PEP 659), so the code “warms up” during its first executions.\n",
    "A single measurement is therefore not enough: we measure many times and report the median.\n",
    "\n",
    "## `%timeit` in the notebook and the `timeit` module\n",
    "\n",
    "In a Jupyter notebook the most convenient tool is the “magic” command `%timeit`. It chooses the\n",
    "number of repetitions by itself and reports the mean with the standard deviation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "06fdedf8",
   "metadata": {},
   "outputs": [],
   "source": [
    "%timeit suma_petla(100)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "603824f3",
   "metadata": {},
   "source": [
    "The command ran the function many times, in seven series. Outside a notebook, the same is provided\n",
    "by the `timeit` module of the standard library, and in a terminal by the command `python -m timeit`.\n",
    "For the duration of the measurement, the `timeit` module turns off the garbage collector and runs\n",
    "the measured code inside a function. We will see in a moment why this second detail matters.\n",
    "\n",
    "## A tool for comparisons\n",
    "\n",
    "In this chapter we compare several variants of the same computation at a time, so a table is more\n",
    "convenient than separate `%timeit` calls. Here is the whole tool. A copy of this cell appears\n",
    "(collapsed) at the beginning of parts 2–7 and 9."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0b92d364",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Narzędzia pomiaru czasu — opisane w części 1 tego rozdziału.\n",
    "import platform\n",
    "import statistics\n",
    "import subprocess\n",
    "import sys\n",
    "import textwrap\n",
    "import timeit\n",
    "from importlib.metadata import version\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter\n",
    "\n",
    "INDYGO, BURSZTYN, ZIELEN = \"#4f46e5\", \"#d97706\", \"#059669\"\n",
    "SZARY, TUSZ, SIATKA = \"#94a3b8\", \"#334155\", \"#e2e8f0\"\n",
    "JEDNOSTKI = ((\"s\", 1.0), (\"ms\", 1e-3), (\"µs\", 1e-6), (\"ns\", 1e-9))\n",
    "\n",
    "\n",
    "def zmierz(f, *args, cel=0.02, proby=7):\n",
    "    \"\"\"Mediana czasu jednego wywołania f(*args), w sekundach.\n",
    "\n",
    "    Szybką funkcję wywołujemy w seriach trwających około `cel` sekund, bo\n",
    "    zegar nie zauważy pojedynczego wywołania trwającego ułamek mikrosekundy.\n",
    "    Z `proby` serii bierzemy medianę, odporną na serie zakłócone przez inne\n",
    "    programy.\n",
    "    \"\"\"\n",
    "    zegar = timeit.Timer(lambda: f(*args))\n",
    "    t = zegar.timeit(number=1)          # rozgrzewka i pierwsza ocena\n",
    "    if t > cel:                         # wolna funkcja: trzy wywołania\n",
    "        return statistics.median(zegar.repeat(repeat=3, number=1))\n",
    "    n = 1\n",
    "    while t < cel / 10:                 # zbyt krótka seria: wydłużamy ją\n",
    "        n *= 10\n",
    "        t = zegar.timeit(number=n)\n",
    "    n = max(1, round(n * cel / t))      # seria trwa teraz około `cel` s\n",
    "    return statistics.median(zegar.repeat(repeat=proby, number=n)) / n\n",
    "\n",
    "\n",
    "def czas(s):\n",
    "    \"\"\"Czas w sekundach jako napis z jednostką, np. 1.23 ms.\"\"\"\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if s >= 0.9995 * skala or jednostka == \"ns\":\n",
    "            v = s / skala\n",
    "            if v >= 99.95:\n",
    "                return f\"{v:.0f} {jednostka}\"\n",
    "            return f\"{v:#.3g} {jednostka}\"\n",
    "\n",
    "\n",
    "def krotnosc(r):\n",
    "    \"\"\"Iloraz czasów jako napis: 340×, 2.5×, 0.81×.\"\"\"\n",
    "    if r >= 10:\n",
    "        return f\"{r:.0f}×\"\n",
    "    return f\"{r:.1f}×\" if r >= 1 else f\"{r:.2f}×\"\n",
    "\n",
    "\n",
    "def porownaj(warianty, *args, zgodne=None):\n",
    "    \"\"\"Mierzy warianty (nazwa → funkcja) na tych samych danych.\n",
    "\n",
    "    Najpierw sprawdza, że wszystkie warianty dają ten sam wynik (operatorem\n",
    "    == albo funkcją `zgodne`): porównujemy tylko programy, które liczą to\n",
    "    samo. Przyspieszenie to czas pierwszego wariantu podzielony przez czas\n",
    "    danego. Zwraca słownik czasów.\n",
    "    \"\"\"\n",
    "    wyniki = {nazwa: f(*args) for nazwa, f in warianty.items()}\n",
    "    wzorzec = next(iter(wyniki.values()))\n",
    "    for nazwa, w in wyniki.items():\n",
    "        if not (zgodne(w, wzorzec) if zgodne else w == wzorzec):\n",
    "            raise AssertionError(f\"wariant „{nazwa}” daje inny wynik\")\n",
    "    czasy = {nazwa: zmierz(f, *args) for nazwa, f in warianty.items()}\n",
    "    baza = next(iter(czasy.values()))\n",
    "    szer = max(len(nazwa) for nazwa in czasy)\n",
    "    wiersze = [f\"{'wariant':{szer}}  {'czas':>9}  {'przyspieszenie':>14}\"]\n",
    "    for nazwa, t in czasy.items():\n",
    "        wiersze.append(f\"{nazwa:{szer}}  {czas(t):>9}\"\n",
    "                       f\"  {krotnosc(baza / t):>14}\")\n",
    "    print(\"\\n\".join(wiersze))\n",
    "    return czasy\n",
    "\n",
    "\n",
    "def srodowisko(*biblioteki):\n",
    "    \"\"\"Wypisuje, na czym mierzymy: procesor, system, Python, biblioteki.\"\"\"\n",
    "    if sys.platform == \"darwin\":\n",
    "        procesor = subprocess.run(\n",
    "            [\"sysctl\", \"-n\", \"machdep.cpu.brand_string\"],\n",
    "            capture_output=True, text=True).stdout.strip()\n",
    "        system = f\"macOS {platform.mac_ver()[0]}\"\n",
    "    else:\n",
    "        procesor = platform.processor()\n",
    "        system = f\"{platform.system()} {platform.release()}\"\n",
    "    opis = [procesor or platform.machine(), system,\n",
    "            f\"Python {platform.python_version()}\"]\n",
    "    opis += [f\"{b} {version(b)}\" for b in biblioteki]\n",
    "    print(textwrap.fill(\"Pomiary: \" + \", \".join(opis), width=79,\n",
    "                        subsequent_indent=\"  \"))\n",
    "\n",
    "\n",
    "def upewnij(warunek, tresc):\n",
    "    \"\"\"Pilnuje zdań z tekstu rozdziału.\n",
    "\n",
    "    Gdy pomiar przeczy zdaniu, budowa książki się zatrzymuje.\n",
    "    \"\"\"\n",
    "    if not warunek:\n",
    "        raise AssertionError(f\"Tekst rozdziału twierdzi: {tresc}. \"\n",
    "                             \"Pomiar temu przeczy.\")\n",
    "\n",
    "\n",
    "def _os_czasu(v, _):\n",
    "    for jednostka, skala in JEDNOSTKI:\n",
    "        if v >= 0.9995 * skala:\n",
    "            return f\"{v / skala:.0f} {jednostka}\"\n",
    "    return f\"{v / 1e-9:g} ns\"\n",
    "\n",
    "\n",
    "def wykres_czasow(czasy, tytul):\n",
    "    \"\"\"Czasy wariantów na osi logarytmicznej; najszybszy jest wyróżniony.\"\"\"\n",
    "    nazwy = list(czasy)[::-1]           # pierwszy wariant na górze\n",
    "    t = [czasy[nazwa] for nazwa in nazwy]\n",
    "    fig, ax = plt.subplots(figsize=(8, 0.42 * len(nazwy) + 1.2))\n",
    "    ax.scatter(t, range(len(nazwy)), s=70, zorder=3, edgecolors=\"white\",\n",
    "               linewidths=2, c=[INDYGO if v == min(t) else SZARY for v in t])\n",
    "    for i, v in enumerate(t):\n",
    "        ax.annotate(czas(v), (v, i), xytext=(9, 0), va=\"center\",\n",
    "                    textcoords=\"offset points\", fontsize=9, color=TUSZ)\n",
    "    ax.set_yticks(range(len(nazwy)), nazwy)\n",
    "    ax.set_xscale(\"log\")\n",
    "    ax.set_xlim(min(t) / 3, max(t) * 8)  # miejsce na etykiety\n",
    "    ax.xaxis.set_major_locator(LogLocator(base=10))\n",
    "    ax.xaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.grid(axis=\"x\", color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\", \"left\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.tick_params(axis=\"y\", length=0)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()\n",
    "\n",
    "\n",
    "def wykres_skalowania(rozmiary, serie, tytul, opis_x=\"n\"):\n",
    "    \"\"\"Czas w zależności od rozmiaru danych, obie osie logarytmiczne.\"\"\"\n",
    "    fig, ax = plt.subplots(figsize=(8, 4))\n",
    "    style = zip(serie.items(), (INDYGO, BURSZTYN, ZIELEN), \"osD\")\n",
    "    for (nazwa, czasy_serii), kolor, znak in style:\n",
    "        ax.loglog(rozmiary, czasy_serii, \"-\", marker=znak, color=kolor,\n",
    "                  lw=2, ms=6, label=nazwa)\n",
    "    ax.set_xticks(rozmiary, [str(n) for n in rozmiary])\n",
    "    ax.xaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.yaxis.set_major_formatter(FuncFormatter(_os_czasu))\n",
    "    ax.yaxis.set_minor_formatter(NullFormatter())\n",
    "    ax.set_xlabel(opis_x)\n",
    "    ax.grid(color=SIATKA, lw=1)\n",
    "    ax.set_axisbelow(True)\n",
    "    for bok in (\"top\", \"right\"):\n",
    "        ax.spines[bok].set_visible(False)\n",
    "    ax.legend(loc=\"best\", frameon=False, fontsize=9)\n",
    "    ax.set_title(tytul, loc=\"left\", fontsize=11)\n",
    "    plt.tight_layout()\n",
    "    plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5c64e602",
   "metadata": {},
   "source": [
    "* `zmierz(f, *args)` calls `f(*args)` in series lasting about $0.02$ s and returns the median, over\n",
    "  seven series, of the time of a single call. The median does not change when another program\n",
    "  disturbs a single series. A slow function (one that takes longer than a series) is called three\n",
    "  times.\n",
    "* `porownaj(warianty, *args)` first checks that all variants give the same result, then measures\n",
    "  the times and prints a table. The speedup is the time of the first variant divided by the time of\n",
    "  the given one; a number less than $1$ means a slowdown.\n",
    "* `srodowisko(...)` prints the computer and the library versions on which we measure.\n",
    "* `upewnij(warunek, tresc)` guards sentences of the chapter’s text, e.g., “variant A is more than\n",
    "  a hundred times faster than B.” Every time the page is built, it checks them against fresh\n",
    "  measurements. If a measurement contradicts a sentence, the build stops. These cells are hidden on\n",
    "  the page, but they are in the downloaded notebook.\n",
    "* `wykres_czasow` and `wykres_skalowania` plot the results on logarithmic axes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "20eeffdc",
   "metadata": {},
   "outputs": [],
   "source": [
    "srodowisko(\"sympy\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6093ae30",
   "metadata": {},
   "source": [
    "```{admonition} Times in this chapter\n",
    ":class: tip\n",
    "All times come from the computer on which this page was built (the line printed by `srodowisko`\n",
    "above), and they change with every build. On your computer they will be different. Ratios of times\n",
    "usually change much less than the times themselves. Download the notebook (the button at the top of\n",
    "the page) and check what they are on your computer.\n",
    "```\n",
    "\n",
    "## A loop in a notebook cell and a loop in a function\n",
    "\n",
    "Code typed directly into a notebook cell runs at module level. The variables `s`, `i`, `j` are then\n",
    "global, and the interpreter looks them up in a namespace dictionary. Inside a function the same\n",
    "variables are local, and the interpreter accesses them by their slot number in the call frame. We\n",
    "imitate a notebook cell by compiling the loop and running it with the function `exec` in a separate\n",
    "namespace dictionary."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d73b77a1",
   "metadata": {},
   "outputs": [],
   "source": [
    "ZRODLO = \"\"\"\n",
    "s = 0\n",
    "for i in range(n):\n",
    "    for j in range(n):\n",
    "        s += i + j\n",
    "\"\"\"\n",
    "kod = compile(ZRODLO, \"<komórka>\", \"exec\")\n",
    "\n",
    "\n",
    "def w_module(n):\n",
    "    nazwy = {\"n\": n}          # słownik nazw, jak w komórce notatnika\n",
    "    exec(kod, nazwy)\n",
    "    return nazwy[\"s\"]\n",
    "\n",
    "\n",
    "czasy_zakresu = porownaj({\"pętla w komórce (poziom modułu)\": w_module,\n",
    "                          \"ta sama pętla w funkcji\": suma_petla}, 100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3ff574b8",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(czasy_zakresu[\"pętla w komórce (poziom modułu)\"]\n",
    "        > 1.3 * czasy_zakresu[\"ta sama pętla w funkcji\"],\n",
    "        \"pętla w funkcji jest wyraźnie szybsza od pętli na poziomie modułu\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b39f20ed",
   "metadata": {},
   "source": [
    "The same loop inside a function runs noticeably faster. The reason can be seen in the bytecode, that\n",
    "is, in the instructions that the interpreter executes. The `dis` module prints them. Let us collect\n",
    "the instructions that read and write variables:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cad0e842",
   "metadata": {},
   "outputs": [],
   "source": [
    "import dis\n",
    "\n",
    "\n",
    "def rozkazy(obiekt):\n",
    "    return sorted({r.opname for r in dis.get_instructions(obiekt)\n",
    "                   if r.opname.startswith((\"LOAD\", \"STORE\"))})\n",
    "\n",
    "\n",
    "print(\"komórka:\", rozkazy(kod))\n",
    "print(\"funkcja:\", rozkazy(suma_petla))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a209038",
   "metadata": {},
   "source": [
    "At module level, variables are handled by the instructions `LOAD_NAME` and `STORE_NAME`, which look\n",
    "the name up in a dictionary. In a function, the instructions `LOAD_FAST` and `STORE_FAST` access\n",
    "a local variable by its number. Only `range` is a global name in the function (`LOAD_GLOBAL`), but\n",
    "we read it only when each loop starts, not for every term of the sum. The practical conclusion:\n",
    "**wrap computations in functions**. The code is then faster, and in addition it is easier to test\n",
    "and to reuse.\n",
    "\n",
    "For the same reason, `%timeit` can be misleading. The command pastes the measured code into\n",
    "a function, so a loop typed into a cell with `%%timeit` is measured as a loop in a function. This can\n",
    "be seen in the source code that the `timeit` module builds before measuring:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf7015be",
   "metadata": {},
   "outputs": [],
   "source": [
    "import timeit\n",
    "\n",
    "print(timeit.Timer(ZRODLO, setup=\"n = 100\").src)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8ac32b67",
   "metadata": {},
   "outputs": [],
   "source": [
    "%%timeit n = 100\n",
    "s = 0\n",
    "for i in range(n):\n",
    "    for j in range(n):\n",
    "        s += i + j"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67dc7a89",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "t_timeit = statistics.median(\n",
    "    timeit.Timer(ZRODLO, setup=\"n = 100\").repeat(repeat=7, number=100)) / 100\n",
    "upewnij(t_timeit < 0.8 * czasy_zakresu[\"pętla w komórce (poziom modułu)\"],\n",
    "        \"%%timeit mierzy pętlę jak w funkcji, a nie jak w komórce\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1aab429e",
   "metadata": {},
   "source": [
    "The time from `%%timeit` is close to the time of the loop in a function, not of the loop executed in\n",
    "a cell, even though in both cases we typed the loop into a cell. The instructor’s study, which\n",
    "compares four versions of CPython, describes the same effect in detail.\n",
    "\n",
    "## Loop, generator, list, formula\n",
    "\n",
    "Let us now compare five ways of computing $S(n)$, all inside functions:\n",
    "\n",
    "1. two nested loops;\n",
    "2. a generator passed to the function `sum`;\n",
    "3. a *list comprehension* passed to the function `sum`;\n",
    "4. the linear sum $2n\\sum_{i<n} i$ from the first step of the proof of the formula;\n",
    "5. the formula $n^2(n-1)$ itself.\n",
    "\n",
    "The first three variants go through all $n^2$ pairs, the fourth through $n$ numbers, and the fifth\n",
    "performs a few arithmetic operations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f0062b76",
   "metadata": {},
   "outputs": [],
   "source": [
    "def suma_generator(n):\n",
    "    return sum(i + j for i in range(n) for j in range(n))\n",
    "\n",
    "\n",
    "def suma_lista(n):\n",
    "    return sum([i + j for i in range(n) for j in range(n)])\n",
    "\n",
    "\n",
    "def suma_liniowa(n):\n",
    "    return 2 * n * sum(range(n))\n",
    "\n",
    "\n",
    "def suma_wzor(n):\n",
    "    return n * n * (n - 1)\n",
    "\n",
    "\n",
    "WARIANTY = {\"dwie pętle\": suma_petla, \"generator w sum\": suma_generator,\n",
    "            \"lista w sum\": suma_lista, \"suma liniowa\": suma_liniowa,\n",
    "            \"wzór n²(n-1)\": suma_wzor}\n",
    "czasy_100 = porownaj(WARIANTY, 100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7734d061",
   "metadata": {},
   "outputs": [],
   "source": [
    "czasy_1000 = porownaj(WARIANTY, 1000)\n",
    "wykres_czasow(czasy_1000, \"Pięć sposobów obliczenia S(1000)\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "07052c2d",
   "metadata": {},
   "outputs": [],
   "source": [
    "PRZEGLAD_PAR = [\"dwie pętle\", \"generator w sum\", \"lista w sum\"]\n",
    "for n_, czasy_n in ((100, czasy_100), (1000, czasy_1000)):\n",
    "    najszybszy = min(PRZEGLAD_PAR, key=czasy_n.get)\n",
    "    rozrzut = max(czasy_n[k] for k in PRZEGLAD_PAR) / czasy_n[najszybszy]\n",
    "    print(f\"n = {n_}: najszybszy z przeglądających pary jest „{najszybszy}”,\")\n",
    "    print(f\"{'':9}najwolniejszy jest od niego {krotnosc(rozrzut)} wolniejszy\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "99fa2f76",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "for czasy_n in (czasy_100, czasy_1000):\n",
    "    upewnij(max(czasy_n[k] for k in PRZEGLAD_PAR)\n",
    "            < 4 * min(czasy_n[k] for k in PRZEGLAD_PAR),\n",
    "            \"warianty przeglądające wszystkie pary różnią się \"\n",
    "            \"mniej niż czterokrotnie\")\n",
    "upewnij(czasy_1000[\"dwie pętle\"] > 100 * czasy_1000[\"suma liniowa\"],\n",
    "        \"suma liniowa jest dla n = 1000 ponad sto razy szybsza od pętli\")\n",
    "upewnij(czasy_1000[\"dwie pętle\"] > 10_000 * czasy_1000[\"wzór n²(n-1)\"],\n",
    "        \"wzór jest dla n = 1000 ponad dziesięć tysięcy razy szybszy od pętli\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7f358595",
   "metadata": {},
   "source": [
    "The three variants that go through all pairs differ from one another by less than a factor of four,\n",
    "and which of them wins depends on $n$ and on the Python version (see the lines below the plot). The\n",
    "instructor’s study shows this in more detail. For small $n$ the list is often the fastest, because\n",
    "its elements are small integers, which Python keeps in memory permanently. For large $n$ the program\n",
    "has to create and free $n^2$ new objects, and the list’s advantage disappears. The last two variants\n",
    "are faster by orders of magnitude: the linear sum more than a hundred times, and the formula more\n",
    "than ten thousand times. Changing the algorithm from $n^2$ operations to $n$ or to a constant number\n",
    "of operations gives more than any change in how the loop is written. This lesson is the subject of\n",
    "{doc}`part 2 <p2_algorytm>`.\n",
    "\n",
    "## Measurement pitfalls\n",
    "\n",
    "It is easy to spoil a time measurement so that it measures something other than we think. Here are\n",
    "the four most common ways.\n",
    "\n",
    "**An exhausted generator.** A generator yields each value only once. A second pass computes\n",
    "nothing:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e9c6b3ea",
   "metadata": {},
   "outputs": [],
   "source": [
    "g = (i + j for i in range(100) for j in range(100))\n",
    "print(sum(g), sum(g))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01b5aa7c",
   "metadata": {},
   "source": [
    "If we measured `sum(g)` repeatedly with a single generator `g`, only the first call would compute\n",
    "the sum. The others would sum an empty sequence. That is why in the tables we always measure a call\n",
    "to a function that creates a new generator.\n",
    "\n",
    "**Caches.** Some libraries remember results. SymPy remembers the results of many operations, so\n",
    "a second expansion of the same expression takes a fraction of the time of the first:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8857c015",
   "metadata": {},
   "outputs": [],
   "source": [
    "from sympy.core.cache import clear_cache\n",
    "\n",
    "x, y = sp.symbols(\"x y\")\n",
    "w = (x + y + 1)**30\n",
    "pomiary = []\n",
    "for _ in range(3):\n",
    "    start = time.perf_counter()\n",
    "    sp.expand(w)\n",
    "    pomiary.append(time.perf_counter() - start)\n",
    "clear_cache()                       # czyścimy pamięć podręczną SymPy\n",
    "start = time.perf_counter()\n",
    "sp.expand(w)\n",
    "pomiary.append(time.perf_counter() - start)\n",
    "print(\"trzy kolejne rozwinięcia:\", \", \".join(czas(t) for t in pomiary[:3]))\n",
    "print(\"po wyczyszczeniu pamięci podręcznej:\", czas(pomiary[3]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "48979dc0",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(pomiary[0] > 50 * pomiary[2] and pomiary[3] > 50 * pomiary[2],\n",
    "        \"powtórzone rozwinięcie korzysta z pamięci podręcznej\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4b0dbbb8",
   "metadata": {},
   "source": [
    "A repeated measurement on the same data would measure the cache, not the expansion of the\n",
    "polynomial. In {doc}`part 7 <p7_sympy>` we clear this cache before every SymPy measurement.\n",
    "\n",
    "**One-time costs.** Importing a library, compilation, and the first, “cold” call are paid for only\n",
    "once. We measure them separately, starting a new Python process each time:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "989174c4",
   "metadata": {},
   "outputs": [],
   "source": [
    "import statistics\n",
    "import subprocess\n",
    "import sys\n",
    "\n",
    "\n",
    "def uruchom(polecenie):\n",
    "    start = time.perf_counter()\n",
    "    subprocess.run([sys.executable, \"-c\", polecenie], check=True)\n",
    "    return time.perf_counter() - start\n",
    "\n",
    "\n",
    "POLECENIA = (\"pass\", \"import math\", \"import numpy\", \"import sympy\")\n",
    "importy = {polecenie: statistics.median(uruchom(polecenie) for _ in range(3))\n",
    "           for polecenie in POLECENIA}\n",
    "for polecenie, t in importy.items():\n",
    "    print(f\"python -c '{polecenie}'\".ljust(28), czas(t))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5484b519",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(importy[\"import sympy\"] > 3 * importy[\"pass\"],\n",
    "        \"import SymPy trwa kilka razy dłużej niż samo uruchomienie Pythona\")\n",
    "upewnij(0.01 <= importy[\"pass\"] < 0.1,\n",
    "        \"samo uruchomienie Pythona trwa kilkanaście–kilkadziesiąt milisekund\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "48bf7bbc",
   "metadata": {},
   "source": [
    "Starting Python alone takes from a dozen to several dozen milliseconds, and importing SymPy several\n",
    "times longer. For a short script these costs can outweigh the computation. They are not, however,\n",
    "part of the computation time, and they must not be mixed with the time of a single call.\n",
    "\n",
    "**Noise.** Let us measure the same function twice, as if it were two different variants:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f50cb65",
   "metadata": {},
   "outputs": [],
   "source": [
    "czasy_szum = porownaj({\"suma_petla\": suma_petla,\n",
    "                       \"suma_petla jeszcze raz\": suma_petla}, 300)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "046ebfe1",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "r = czasy_szum[\"suma_petla\"] / czasy_szum[\"suma_petla jeszcze raz\"]\n",
    "upewnij(0.7 < r < 1.4, \"dwa pomiary tej samej funkcji są prawie równe\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "da81c20d",
   "metadata": {},
   "source": [
    "The speedup should be $1$, and it is almost $1$. The difference is measurement noise. That is why we\n",
    "do not treat differences of a few percent as a result. We are interested in differences by a factor\n",
    "of several or more, and also in how the time grows with the size of the data.\n",
    "\n",
    "## Where the time goes: the profiler\n",
    "\n",
    "Before we start speeding up a program, we need to know which part of it takes the time. This is what\n",
    "the profiler `cProfile` is for: it counts the calls of each function and the time spent in it and in\n",
    "the functions it calls. Let us take the trapezoidal rule for $\\int_0^1 e^{-x^2}\\,dx$, in which we\n",
    "compute the values of the function by substitution in SymPy, as in many places in Lecture 5."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c9a89758",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cProfile\n",
    "import pstats\n",
    "\n",
    "\n",
    "def trapezy_sympy(n):\n",
    "    \"\"\"Metoda trapezów; wartości funkcji przez podstawienie w SymPy (wolno).\"\"\"\n",
    "    x = sp.symbols(\"x\")\n",
    "    f = sp.exp(-x**2)\n",
    "    h = sp.Rational(1, n)\n",
    "    ys = [float(f.subs(x, k * h)) for k in range(n + 1)]\n",
    "    return (sum(ys) - (ys[0] + ys[-1]) / 2) / n\n",
    "\n",
    "\n",
    "def profil(f, *args, ile=6):\n",
    "    \"\"\"Najdroższe funkcje według czasu łącznego (z wywoływanymi).\"\"\"\n",
    "    clear_cache()\n",
    "    p = cProfile.Profile()\n",
    "    p.runcall(f, *args)\n",
    "    statystyki = pstats.Stats(p).stats\n",
    "    calosc = max(s[3] for s in statystyki.values())\n",
    "    print(f\"{'wywołań':>8} {'czas łączny':>12}  funkcja\")\n",
    "    wiersze = sorted(statystyki.items(), key=lambda kv: -kv[1][3])\n",
    "    for (plik, _, nazwa), (_, wywolan, _, laczny, _) in wiersze[:ile]:\n",
    "        if \"site-packages/\" in plik:      # funkcja z biblioteki: moduł i nazwa\n",
    "            nazwa = plik.split(\"site-packages/\")[-1] + \":\" + nazwa\n",
    "        print(f\"{wywolan:8} {czas(laczny):>12}  {nazwa}\")\n",
    "    return statystyki, calosc\n",
    "\n",
    "\n",
    "statystyki, calosc = profil(trapezy_sympy, 200)\n",
    "w_subs = sum(s[3] for (plik, _, nazwa), s in statystyki.items()\n",
    "             if nazwa == \"subs\" and \"sympy\" in plik)\n",
    "print(f\"podstawienia subs zajęły {w_subs / calosc:.0%} czasu\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "338f77af",
   "metadata": {
    "tags": [
     "remove-cell"
    ]
   },
   "outputs": [],
   "source": [
    "upewnij(w_subs / calosc > 0.5, \"większość czasu zajmuje podstawianie subs\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "62fa17ab",
   "metadata": {},
   "source": [
    "The profiler points to the culprit: most of the time is taken by `subs`, that is, by substituting\n",
    "numbers into a symbolic expression. Our own arithmetic (summing and dividing) hardly matters. So it\n",
    "is the substitution that is worth speeding up, not the loop. In {doc}`part 7 <p7_sympy>` we will\n",
    "replace `subs` with the function `sp.lambdify`, and the same computation will become thousands of\n",
    "times faster.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* First the **contract**: we compare only variants that give the same result, and we check this\n",
    "  before measuring.\n",
    "* We measure **many times** and report the median (`%timeit`, `timeit`, our `porownaj`). Differences\n",
    "  of a few percent are noise.\n",
    "* **Wrap computations in functions**: local variables are faster than global ones, and `%timeit`\n",
    "  measures code as if it were in a function anyway.\n",
    "* Beware of **exhausted generators**, library **caches**, and **one-time costs** (the import, the\n",
    "  first call).\n",
    "* Before we start speeding things up, we **profile**: `cProfile` shows where the time really goes.\n",
    "* Changing the algorithm (here: from $n^2$ operations to a constant number) gives more than any\n",
    "  change in how the loop is written.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. ★ Measure `suma_petla(n)` for $n=100, 200, 400, 800$. By what factor does the time grow when $n$\n",
    "   doubles? Explain this by the number of additions performed.\n",
    "2. ★ On your computer, check the table of the five variants for $n=100$ and $n=3000$. Which of the\n",
    "   three variants that go through the pairs wins? Compare with the results on this page.\n",
    "3. ★★ Write a variant in which the inner loop is replaced by a formula for the sum\n",
    "   $\\sum_{j<n}(i+j)$. How many operations does it perform? Measure it together with the others.\n",
    "4. ★★ Measure `%timeit sp.expand((x + y + 1)**30)` and compare it with a measurement in which you\n",
    "   first call `clear_cache()` in every repetition. Which measurement answers the question “how long\n",
    "   does it take to expand the polynomial?”"
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "default_lexer": "ipython3"
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
