{
  "cells": [
    {
      "cell_type": "code",
      "source": [
        "import json\n",
        "from pathlib import Path\n",
        "\n",
        "import pandas\n",
        "from IPython.display import display, IFrame, Markdown\n",
        "from plotly import express"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false,
        "outputHidden": false,
        "inputHidden": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "render_format = 'svg'\n",
        "benchmark_path = Path()\n",
        "df_dict = {}\n",
        "stat_dict = {}\n",
        "for p in benchmark_path.glob('build-*-result.json'):\n",
        "    build_name = p.stem.split('-', 2)[1]\n",
        "    for browser_data in json.loads(p.read_text()):\n",
        "        browser_name = f'{browser_data[\"browser\"][\"name\"]} {browser_data[\"browser\"][\"major\"]}'\n",
        "        browser_name = browser_name.lower().replace('chrome headless', 'chromium')\n",
        "        for result in (r for i, r in browser_data['result'].items() if i.isdigit()):\n",
        "            key = build_name, browser_name, result['name']\n",
        "            df_dict[key] = result['stats']['sample']\n",
        "            stat_dict[key] = result['stats']\n",
        "\n",
        "min_sample_size = min(len(v) for v in df_dict.values())\n",
        "df_dict = {k: v[:min_sample_size] for k, v in df_dict.items()}\n",
        "            \n",
        "wide_df = pandas.DataFrame(df_dict).reset_index()\n",
        "df = pandas.melt(\n",
        "    wide_df, \n",
        "    id_vars='index', \n",
        "    var_name=['build', 'browser', 'test'], \n",
        "    value_name='duration',\n",
        ")\n",
        "df = df.rename(columns={'index': 'run'})\n",
        "df.sort_values(['build', 'run'], inplace=True)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "inputHidden": true,
        "outputExpanded": false
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# sql.js build comparison\n",
        "\n",
        "<style>\n",
        "@page {\n",
        "  size: 215mm 297mm;\n",
        "  margin: 0;\n",
        "}\n",
        "</style>"
      ],
      "metadata": {}
    },
    {
      "cell_type": "code",
      "source": [
        "!du -b lib | head -n 2"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false,
        "outputHidden": false,
        "inputHidden": true
      }
    },
    {
      "cell_type": "code",
      "source": [
        "stat_df = pandas.DataFrame(stat_dict)\n",
        "stat_df = stat_df.loc[['mean', 'rme']].transpose()\n",
        "stat_df.index = stat_df.index.set_names(['build', 'browser', 'test'])\n",
        "stat_df = stat_df.reset_index().sort_values(['test', 'browser'], ascending=False)\n",
        "for index, row in stat_df.iterrows():\n",
        "    print('\\t'.join([\n",
        "        row['build'],\n",
        "        row['browser'],\n",
        "        row['test'],\n",
        "        f'{row[\"mean\"]:.2f} s ± {row[\"rme\"]:.1f}%'\n",
        "    ]))"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "inputHidden": true,
        "outputExpanded": false
      }
    },
    {
      "cell_type": "code",
      "source": [
        "fig = express.box(df, x='browser', y='duration', points='all', color='build', facet_row='test')\n",
        "fig.update_yaxes(matches=None)\n",
        "fig.show(render_format)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "inputHidden": true,
        "outputExpanded": false
      }
    },
    {
      "cell_type": "code",
      "source": [
        "fig = express.line(\n",
        "    df, x='run', y='duration', color='build', facet_col='browser', facet_row='test'\n",
        ")\n",
        "fig.update_yaxes(matches=None)\n",
        "fig.show(render_format)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "inputHidden": true,
        "outputExpanded": false
      }
    },
    {
      "cell_type": "code",
      "source": [
        "plot_df = df.groupby(['browser', 'build', 'test'])['duration'].mean().reset_index()\n",
        "plot_df['pct'] = (\n",
        "    plot_df\n",
        "    .groupby(['browser', 'test'])['duration']\n",
        "    .pct_change()\n",
        "    .fillna('')\n",
        "    .map(lambda v: '{:.2%}'.format(v) if v else v)\n",
        ")\n",
        "fig = express.bar(\n",
        "    plot_df, \n",
        "    x='browser', \n",
        "    y='duration', \n",
        "    color='build', \n",
        "    text='pct', \n",
        "    barmode='overlay', \n",
        "    facet_row='test',\n",
        ")\n",
        "fig.update_yaxes(matches=None)\n",
        "fig.show(render_format)"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "inputHidden": true,
        "outputExpanded": false
      }
    },
    {
      "cell_type": "code",
      "source": [
        "for p in sorted(benchmark_path.glob('build-*.svg')):\n",
        "    display(Markdown(p.stem))\n",
        "    display(IFrame(p, 640, 480))"
      ],
      "outputs": [],
      "execution_count": null,
      "metadata": {
        "collapsed": false,
        "outputHidden": false,
        "inputHidden": true,
        "outputExpanded": false
      }
    }
  ],
  "metadata": {
    "kernelspec": {
      "name": "stats",
      "language": "python",
      "display_name": "Stats (Python 3.10)"
    },
    "language_info": {
      "name": "python",
      "version": "3.10.14",
      "mimetype": "text/x-python",
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "pygments_lexer": "ipython3",
      "nbconvert_exporter": "python",
      "file_extension": ".py"
    },
    "widgets": {
      "application/vnd.jupyter.widget-state+json": {
        "state": {},
        "version_major": 2,
        "version_minor": 0
      }
    },
    "kernel_info": {
      "name": "stats"
    },
    "nteract": {
      "version": "0.14.5"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}