diff --git a/codespeed/static/js/comparison.js b/codespeed/static/js/comparison.js index 72016f5c..594c8928 100644 --- a/codespeed/static/js/comparison.js +++ b/codespeed/static/js/comparison.js @@ -41,16 +41,57 @@ function getConfiguration() { }; } +// (exe, env) combinations that have at least one result for the selected benchmarks +function pairsWithData(exes, enviros, bens) { + var pairs = []; + if (!compdata) { return pairs; } + for (var x = 0; x < exes.length; x++) { + for (var e = 0; e < enviros.length; e++) { + var d = compdata[exes[x]] && compdata[exes[x]][enviros[e]]; + if (!d) { continue; } + for (var b = 0; b < bens.length; b++) { + if (d[bens[b]] !== null && d[bens[b]] !== undefined) { + pairs.push([exes[x], enviros[e]]); + break; + } + } + } + } + return pairs; +} + function updateGraphTitle(exes, enviros, bens, baseline, chart, chartTitles) { var $title = $("#graph-title"); var isPair = (exes.length === 2 && enviros.length === 1) || (exes.length === 1 && enviros.length === 2); - if (isPair && chart !== "stacked bars" && compdata) { + var dataPairs = isPair ? [] : pairsWithData(exes, enviros, bens); + if ((isPair || dataPairs.length === 2) && chart !== "stacked bars" && compdata) { // Resolve which (exe, env) pair is "other" vs "base" var otherExe, otherEnv, baselineExe, baselineEnv; - if (exes.length === 1 && enviros.length === 2) { + if (!isPair) { + // Several exes/envs selected, but only two combinations have results + var baseIdx = 0; + if (baseline !== "none") { + var bp = baseline.split('@'); + baseIdx = -1; + for (var i = 0; i < dataPairs.length; i++) { + if (dataPairs[i][0] === bp[0] && (bp.length === 1 || dataPairs[i][1] === bp[1])) { + baseIdx = i; + break; + } + } + if (baseIdx === -1) { + $title.text(chartTitles.join(' / ')); + return; + } + } + baselineExe = dataPairs[baseIdx][0]; + baselineEnv = dataPairs[baseIdx][1]; + otherExe = dataPairs[1 - baseIdx][0]; + otherEnv = dataPairs[1 - baseIdx][1]; + } else if (exes.length === 1 && enviros.length === 2) { // Same exe, two environments — only show geomean when an explicit baseline env is set if (baseline === "none") { $title.text(chartTitles.join(' / ')); @@ -117,10 +158,10 @@ function updateGraphTitle(exes, enviros, bens, baseline, chart, chartTitles) { var otherLabel = getExeLabel(otherExe); var baselineLabel = getExeLabel(baselineExe); - if (exes.length === 1) { + if (exes.length === 1 || (!isPair && otherEnv !== envForBase)) { otherLabel += ' @ ' + $("label[for='env_" + otherEnv + "']").text().trim(); baselineLabel += ' @ ' + $("label[for='env_" + envForBase + "']").text().trim(); - } else if (baselineEnv !== null) { + } else if (baselineEnv !== null && isPair) { baselineLabel += ' @ ' + $("label[for='env_" + baselineEnv + "']").text().trim(); } diff --git a/codespeed/views.py b/codespeed/views.py index e74d3a37..cb760cc5 100644 --- a/codespeed/views.py +++ b/codespeed/views.py @@ -32,7 +32,7 @@ logger = logging.getLogger(__name__) -# Fraction of the plottable benchmark set a revision must have legacy results +# Fraction of the plottable benchmark set a revision must have results # for before gethistoricaldata() will render it as the 'latest' column. Runs # glitch and drop individual benchmarks, so this is deliberately below 1.0. LATEST_MIN_COVERAGE = 0.8 @@ -111,6 +111,9 @@ def gethistoricaldata(request): # 'labels' maps each key in tagged_revs (plus baseline and 'latest') to # a two-line label [tag, project] for the x axis of the history chart. data = {'results': {}, 'benchmarks': [], 'labels': {}} + source = request.GET.get('source', 'legacy') + if source not in ('legacy', 'pyperformance'): + return HttpResponseBadRequest('unknown source') env = Environment.objects.all() if settings.DEF_ENVIRONMENT: env = env.get(name=settings.DEF_ENVIRONMENT) @@ -133,13 +136,13 @@ def gethistoricaldata(request): data['labels'][resname] = [rev0.tag, baseline_exe.project.name] baseline_results.append((resname, Result.objects.filter( executable=baseline_exe, revision=rev0, environment=env, - benchmark__source='legacy'))) + benchmark__source=source))) if not baseline_results[-1][1]: logger.error('Could not find results for {} rev="{}" env="{}"'.format( baseline_exe, rev0, env)) default_results = {} - all_taggedrevs = [] + data['tagged_revs'] = [] for executable in settings.DEF_EXECUTABLES[::-1]: _def_name = executable['name'] _def_project = Project.objects.get(name=executable['project']) @@ -152,18 +155,19 @@ def gethistoricaldata(request): default_taggedrevs = Revision.objects.filter( branch=_default_branch ).exclude(tag="").order_by('date') - all_taggedrevs += default_taggedrevs for rev in default_taggedrevs: - # Filter to legacy only; pyperformance history can get its own panel later + # A tag can sit on several revisions (e.g. a re-tagged release) + if rev.tag in default_results: + continue res = Result.objects.filter( executable=_default_exe, revision=rev, environment=env, - benchmark__source='legacy') + benchmark__source=source) if not res: logger.info("no results for '%s' '%s' '%s'" % (str(_default_exe), str(rev), str(env))) continue default_results[rev.tag] = res data['labels'][rev.tag] = [rev.tag, _default_exe.project.name] - data['tagged_revs'] = [rev.tag for rev in all_taggedrevs if rev.tag in default_results] + data['tagged_revs'].append(rev.tag) # Fetch data for latest results executable = settings.DEF_EXECUTABLES[0] def_name = executable['name'] @@ -176,27 +180,27 @@ def gethistoricaldata(request): revs = Revision.objects.filter( branch=default_branch).order_by('-date')[:100] # The benchmarks the plots can actually use: those the baseline and every - # tagged revision all have legacy results for. A benchmark missing from any + # tagged revision all have results for. A benchmark missing from any # of them is dropped client side, so it cannot count towards coverage. plottable = {res.benchmark.name for res in baseline_results[0][1]} for tag in data['tagged_revs']: plottable &= {res.benchmark.name for res in default_results[tag]} required = len(plottable) * LATEST_MIN_COVERAGE - # Accept a revision as 'latest' only once its legacy run has covered enough + # Accept a revision as 'latest' only once its run has covered enough # of that set, otherwise fall back to the previous one that has. for rev in revs: latest_results = Result.objects.filter( executable=default_exe, revision=rev, environment=env, - benchmark__source='legacy') + benchmark__source=source) covered = plottable & {res.benchmark.name for res in latest_results} if covered and len(covered) >= required: default_results['latest'] = latest_results break logger.info( "skipping '%s' as 'latest': %d of %d plottable benchmarks have " - "legacy results for '%s'" % ( - str(rev), len(covered), len(plottable), str(env))) + "%s results for '%s'" % ( + str(rev), len(covered), len(plottable), source, str(env))) else: logger.error( "no revision covers %.0f%% of the %d plottable benchmarks for " diff --git a/speed_pypy/templates/embed_comparison.html b/speed_pypy/templates/embed_comparison.html index 13acb984..919011d5 100644 --- a/speed_pypy/templates/embed_comparison.html +++ b/speed_pypy/templates/embed_comparison.html @@ -21,9 +21,18 @@ font-family: sans-serif; color: var(--chart-text); } + #full-results { + position: absolute; + top: 4px; + right: 8px; + z-index: 1; + font: 12px sans-serif; + color: var(--chart-text); + } + {% if full_results_url %}{% endif %}
@@ -61,6 +70,17 @@ }); applyTheme(resolveTheme()); + // Only the fastest and slowest few benchmarks fit; the rest collapse into a gap + // A phone counts as narrow even when the embedding page has no viewport + // meta and lays itself (and so this frame) out at desktop width + function isNarrow() { return Math.min(window.innerWidth, screen.width) <= 760; } + var wasNarrow = isNarrow(); + // Such a page is shrunk to fit the phone, so grow the text to match + function fontScale() { + return isNarrow() ? Math.min(2.5, Math.max(1, window.innerWidth / screen.width)) : 1; + } + var plotData = null; + function renderplot(data) { var wrap = document.getElementById('baseline-comparison-plot'); if (data === null || data.length === 0 || @@ -69,43 +89,86 @@ return; } - var benchmarks = [], latestValues = [], baselineValues = []; - var tagged_data = []; - for (var i in data['tagged_revs']) { tagged_data[i] = []; } - + var rows = []; for (var bench in data['benchmarks']) { var benchname = data['benchmarks'][bench]; - var add_to_tagged_data = true; + var complete = true; for (var i in data['tagged_revs']) { - var rev = data['tagged_revs'][i]; - if (data['results'][benchname][rev] === 0) { add_to_tagged_data = false; break; } - tagged_data[i].push(data['results'][benchname][rev] / data['results'][benchname][data['baseline']]); + if (data['results'][benchname][data['tagged_revs'][i]] === 0) { complete = false; break; } } - if (!add_to_tagged_data) { continue; } + if (!complete) { continue; } var rel = data['results'][benchname]['latest'] / data['results'][benchname][data['baseline']]; - // Drop a benchmark the latest run is missing before pushing its - // label, so the bars stay aligned with the x axis ticks. - // (!(rel > 0) also catches the NaN from a missing value.) + // (!(rel > 0) also catches the NaN from a missing value) if (!(rel > 0)) { continue; } - benchmarks.push(benchname); - latestValues.push(rel); - baselineValues.push(1.0); + rows.push({name: benchname, rel: rel}); } - if (benchmarks.length === 0) { + if (rows.length === 0) { wrap.innerHTML = 'No complete benchmark run available yet'; return; } + rows.sort(function(x, y) { return x.rel - y.rel; }); + plotData = {rows: rows, baseline: data['baseline']}; + drawChart(); + } + + // On our own home page the title carries this link; elsewhere (pypy.org) + // it is the only way to the benchmarks the plot leaves out + function embeddedOnOwnSite() { + try { return window.parent !== window && !!window.parent.document; } + catch (e) { return false; } + } + + function drawChart() { + var rows = plotData.rows; + var keep = isNarrow() ? 10 : 20; + var shown = rows; + if (rows.length > 2 * keep) { + shown = rows.slice(0, keep).concat([null], rows.slice(rows.length - keep)); + } + var labels = shown.map(function(r) { return r ? r.name : '\u2026'; }); + // Floating bars from the baseline at 1.0, so faster runs hang below it + var bars = shown.map(function(r) { return r ? [1, r.rel] : null; }); + var gap = shown.indexOf(null); + var scale = fontScale(); + Chart.defaults.font.size = Math.round(12 * scale); + // Mark the gap on the plot itself, not just on the axis + var gapMarker = { + id: 'gapMarker', + afterDatasetsDraw: function(chart) { + if (gap === -1) { return; } + var ctx = chart.ctx; + ctx.save(); + ctx.font = 'bold ' + Math.round(32 * scale) + 'px sans-serif'; + ctx.fillStyle = Chart.defaults.color; + ctx.textAlign = 'center'; + ctx.textBaseline = 'bottom'; + ctx.fillText('\u2026', chart.scales.x.getPixelForValue(gap), + chart.scales.y.getPixelForValue(1) - 4); + ctx.restore(); + } + }; + if (comparisonChart) { comparisonChart.destroy(); } + var wrap = document.getElementById('baseline-comparison-plot'); + wrap.innerHTML = ''; var canvas1 = document.createElement('canvas'); wrap.appendChild(canvas1); + $('#full-results').prop('hidden', embeddedOnOwnSite() || shown.length === rows.length); + // Let the embedding page title the plot with how much of it is shown + if (window.parent !== window) { + window.parent.postMessage({codespeedBenchmarks: { + total: rows.length, shown: shown.length - (gap === -1 ? 0 : 1) + }}, '*'); + } comparisonChart = new Chart(canvas1, { type: 'bar', + plugins: [gapMarker], data: { - labels: benchmarks, + labels: labels, datasets: [ - {label: 'latest {{ default_exe }}', data: latestValues, backgroundColor: '#4e79a7'}, - {label: data['baseline'], data: baselineValues, type: 'line', + {label: 'latest {{ default_exe }}', data: bars, backgroundColor: '#4e79a7'}, + {label: plotData.baseline, data: shown.map(function() { return 1; }), type: 'line', borderColor: '#f28e2b', backgroundColor: 'transparent', pointRadius: 0, borderWidth: 2, fill: false} ] @@ -115,18 +178,44 @@ responsive: true, maintainAspectRatio: false, plugins: { - tooltip: {position: 'cursor'} + tooltip: { + position: 'cursor', + filter: function(item) { return item.datasetIndex === 0; }, + callbacks: { + label: function(ctx) { + var rel = ctx.raw[1]; + return rel.toFixed(2) + ' (' + (rel < 1 + ? (1 / rel).toFixed(1) + 'x faster)' + : rel.toFixed(1) + 'x slower)'); + } + } + } }, scales: { - x: {ticks: {maxRotation: 70, minRotation: 70, autoSkip: false, font: {size: 11}}}, - y: {min: 0, max: 2.0, ticks: {callback: function(v) { return v.toFixed(2); }}} + x: {ticks: {maxRotation: 70, minRotation: 70, autoSkip: false, + font: function(c) { + return c.index === gap ? {size: Math.round(20 * scale), weight: 'bold'} + : {size: Math.round(11 * scale)}; + }}}, + y: {type: 'logarithmic', + min: 0.005, max: 5, + title: {display: true, + text: 'Relative time (log scale)'}, + ticks: {callback: function(v) { + var m = v / Math.pow(10, Math.floor(Math.log10(v) + 1e-9)); + return [1, 2, 5].some(function(k) { return Math.abs(m - k) < 1e-6; }) + ? String(+v.toPrecision(2)) : ''; + }}} } } }); } + window.addEventListener('resize', function() { + if (plotData && isNarrow() !== wasNarrow) { wasNarrow = isNarrow(); drawChart(); } + }); $(function() { - $.getJSON("{% url 'gethistoricaldata' %}", renderplot); + $.getJSON("{% url 'gethistoricaldata' %}", {source: '{{ source }}'}, renderplot); }); diff --git a/speed_pypy/templates/home.html b/speed_pypy/templates/home.html index 9b3fc228..eb17720f 100644 --- a/speed_pypy/templates/home.html +++ b/speed_pypy/templates/home.html @@ -28,21 +28,55 @@

Comparison

{% if show_historical %}

How fast is {{ default_exe.project }}?

- -

Plot 1: The above plot represents {{ default_exe.project }} ({{ default_exe }}) benchmark times normalized to {{ baseline }}. Smaller is better.

-

It depends greatly on the type of task being performed. The geometric average of all benchmarks is or times faster than {{ baseline }}

+ {% for source, label, url in sources %} +
+

{{ label }} benchmarks{% if url %} {% endif %}

+ +
+ {% endfor %} +

{{ default_exe.project }} ({{ default_exe }}) benchmark times normalized to {{ baseline }}. Smaller is better.

+

Performance depends greatly on the type of task being performed. The geometric average is{% for source, label, url in sources %}{% if not forloop.first %}{% if forloop.last %} and{% else %},{% endif %}{% endif %} or times faster for the {{ label }} benchmarks{% endfor %}, compared to {{ baseline }}.

How has PyPy performance evolved over time?

-
-

Plot 2: Speedup compared to {{ baseline }}, using the inverse of the geometric average of normalized times, out of benchmarks (see paper on why the geometric mean is better for normalized results).

+
+ {% for source, label, url in sources %} +
+

{{ label }} benchmarks

+
+
+ {% endfor %} +
+

Speedup compared to {{ baseline }}, using the inverse of the geometric average of normalized times, out of{% for source, label, url in sources %}{% if not forloop.first %} and{% endif %} {{ label }}{% endfor %} benchmarks (see paper on why the geometric mean is better for normalized results). Larger is better.

{% endif %} {% endblock body %} +{% block extra_head %} +{{ block.super }} + +{% endblock extra_head %} + {% block extra_script %} {{ block.super }} {% if show_historical %} @@ -69,7 +103,7 @@

How has PyPy performance evolved over time?

}; // Chart.js draws its own axis text and grid lines, so hand it the theme colours - var historicalChart = null; + var historicalCharts = {}; function applyChartTheme() { var colors = Theme.chartColors(); Chart.defaults.color = colors.text; @@ -78,21 +112,47 @@

How has PyPy performance evolved over time?

applyChartTheme(); Theme.onChange(function(theme) { applyChartTheme(); - if (historicalChart) { historicalChart.update(); } - // Plot 1 lives in the iframe, which cannot see this page's theme change - var frame = document.querySelector('#historical iframe'); - if (frame && frame.contentWindow) { - frame.contentWindow.postMessage({codespeedTheme: theme}, window.location.origin); - } + Object.values(historicalCharts).forEach(function(c) { c.update(); }); + // The comparison plots live in iframes, which cannot see this page's theme change + document.querySelectorAll('#historical iframe').forEach(function(frame) { + if (frame.contentWindow) { + frame.contentWindow.postMessage({codespeedTheme: theme}, window.location.origin); + } + }); + }); + + // Each comparison iframe reports how many benchmarks it has and shows + window.addEventListener('message', function(e) { + if (e.origin !== window.location.origin || !e.data || !e.data.codespeedBenchmarks) { return; } + document.querySelectorAll('#historical iframe').forEach(function(frame) { + if (frame.contentWindow !== e.source) { return; } + var source = frame.getAttribute('data-source'); + var counts = e.data.codespeedBenchmarks; + var $title = $('#comparison-title-' + source); + var truncated = counts.shown < counts.total; + $title.find('.title-text').text(counts.total + ' ' + $title.data('label') + + ' benchmarks (' + counts.shown + ' shown' + (truncated ? ',' : ')')); + // Wrap the link into the parenthesis only when something is hidden + $title.find('.see-all').prop('hidden', !truncated) + .next('.see-all-close').remove(); + if (truncated) { $title.find('.see-all').after(')'); } + }); }); - function renderplot(data) { + // Phones lay this page out at desktop width and shrink it, so the comparison + // frames grow their text; give the taller rotated labels room + if (Math.min(window.innerWidth, screen.width) <= 760) { + $('#historical iframe').css('height', '650px'); + } + + function renderplot(source, data) { + var $plot = $("#historical-plot-" + source); if (data === null || data.length === 0) { - $("#historical-plot").html(getLoadText('Error retrieving data', 0)); + $plot.html(getLoadText('Error retrieving data', 0)); return; } if (typeof data === 'string' || data instanceof String) { - $("#historical-plot").html(getLoadText('Error retrieving data ' + data, 0)); + $plot.html(getLoadText('Error retrieving data ' + data, 0)); return; } @@ -123,12 +183,12 @@

How has PyPy performance evolved over time?

if (latestValues.length === 0) { // No usable latest run: report nothing rather than a bogus 1.0x. trunk_geomean = NaN; - $('#geomean').html('n/a'); - $('#geofaster').html('n/a'); + $('#geomean-' + source).html('n/a'); + $('#geofaster-' + source).html('n/a'); } else { trunk_geomean = Math.pow(trunk_geomean, 1 / latestValues.length); - $('#geomean').html(trunk_geomean.toFixed(2)); - $('#geofaster').html((1 / trunk_geomean).toFixed(1)); + $('#geomean-' + source).html(trunk_geomean.toFixed(2)); + $('#geofaster-' + source).html((1 / trunk_geomean).toFixed(1)); } // Plot 1 (per-benchmark normalized comparison) is rendered by the @@ -147,7 +207,7 @@

How has PyPy performance evolved over time?

geomeans.push(1 / Math.pow(tempgeo, 1 / tagged_data[i].length)); } geomeans.push(1 / trunk_geomean); - $('#num_of_benchs').html(num_of_benchs); + $('#num_of_benchs-' + source).html(num_of_benchs); // Two-line labels: [tag, project]; fall back to the key itself. var labelFor = function(key) { return (data['labels'] || {})[key] || key; }; @@ -155,10 +215,10 @@

How has PyPy performance evolved over time?

for (var i in data['tagged_revs']) { ticks2.push(labelFor(data['tagged_revs'][i])); } ticks2.push(labelFor('latest')); - var wrap2 = document.getElementById('historical-plot'); + var wrap2 = $plot[0]; var canvas2 = document.createElement('canvas'); wrap2.appendChild(canvas2); - historicalChart = new Chart(canvas2, { + historicalCharts[source] = new Chart(canvas2, { type: 'bar', data: { labels: ticks2, @@ -181,6 +241,18 @@

How has PyPy performance evolved over time?

} } }); + syncHistoricalAxes(); + } + + // Both history plots share the legacy plot's y axis so their bars compare + function syncHistoricalAxes() { + var legacy = historicalCharts['legacy']; + if (!legacy) { return; } + Object.keys(historicalCharts).forEach(function(source) { + if (source === 'legacy') { return; } + historicalCharts[source].options.scales.y.max = legacy.scales.y.max; + historicalCharts[source].update(); + }); } {% endif %} @@ -191,7 +263,10 @@

How has PyPy performance evolved over time?

{% endif %} {% if show_historical %} - $.getJSON("{% url "gethistoricaldata" %}", renderplot); + ['legacy', 'pyperformance'].forEach(function(source) { + $.getJSON("{% url "gethistoricaldata" %}", {source: source}, + function(data) { renderplot(source, data); }); + }); {% endif %} }); diff --git a/speed_pypy/urls.py b/speed_pypy/urls.py index 17346da0..9c5d7299 100644 --- a/speed_pypy/urls.py +++ b/speed_pypy/urls.py @@ -8,6 +8,7 @@ re_path(r'^admin/download-db/$', admin_views.download_db, name='admin-download-db'), re_path(r'^admin/', admin.site.urls), re_path(r'^embed/comparison/$', views.embed_comparison, name='embed-comparison'), + re_path(r'^$', views.PyPyHomeView.as_view(), name='home'), re_path(r'^', include('codespeed.urls')) ] diff --git a/speed_pypy/views.py b/speed_pypy/views.py index 4919dbda..e57086b9 100644 --- a/speed_pypy/views.py +++ b/speed_pypy/views.py @@ -1,22 +1,70 @@ """Views specific to speed.pypy.org.""" import logging +from urllib.parse import urlencode from django.conf import settings from django.shortcuts import render +from django.urls import reverse from django.views.decorators.clickjacking import xframe_options_exempt from django.views.decorators.http import require_GET -from codespeed.models import Executable, Project +from codespeed.models import Environment, Executable, Project, Revision +from codespeed.views import HomeView logger = logging.getLogger(__name__) +# (source, label) of the benchmark suites graphed side by side on the home page +HOME_SOURCES = [('legacy', 'Legacy'), ('pyperformance', 'pyperformance')] + + +def full_results_url(request, source): + """Absolute comparison-page link showing every `source` benchmark for the + latest default executable against the first baseline, or None.""" + try: + def_project = Project.objects.get(name=settings.DEF_EXECUTABLES[0]['project']) + default_exe = Executable.objects.get( + name=settings.DEF_EXECUTABLES[0]['name'], project=def_project) + baseline_exe = Executable.objects.get(name=settings.DEF_BASELINES[0]['executable']) + baseline_rev = Revision.objects.filter( + branch__project=baseline_exe.project, + tag=settings.DEF_BASELINES[0]['revision']).first() + if baseline_rev is None: + return None + baseline_key = '%d:%d' % (baseline_exe.id, baseline_rev.id) + query = { + 'exe': '%d:L:%s,%s' % (default_exe.id, def_project.default_branch, baseline_key), + 'ben': source, + 'hor': 'true', + 'bas': baseline_key, + 'chart': 'normal bars', + } + if settings.DEF_ENVIRONMENT: + query['env'] = Environment.objects.get(name=settings.DEF_ENVIRONMENT).id + except Exception as e: + logger.error('full_results_url: %s', e) + return None + return request.build_absolute_uri( + reverse('comparison') + '?' + urlencode(query, safe=':,')) + + +class PyPyHomeView(HomeView): + + def get_context_data(self, **kwargs): + context = super().get_context_data(**kwargs) + context['sources'] = [(source, label, full_results_url(self.request, source)) + for source, label in HOME_SOURCES] + return context + @require_GET @xframe_options_exempt def embed_comparison(request): """Frame-exempt page rendering only the baseline-comparison for embedding on pypy.org""" - context = {} + source = request.GET.get('source', 'legacy') + if source not in ('legacy', 'pyperformance'): + source = 'legacy' + context = {'source': source, 'full_results_url': full_results_url(request, source)} try: context['baseline'] = Executable.objects.get( name=settings.DEF_BASELINES[0]['executable'])