Completed
Push — master ( 7b504c...b6f606 )
by Ionel Cristian
01:16
created

src.pytest_benchmark.TableResults.display()   F

Complexity

Conditions 22

Size

Total Lines 103

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 22
dl 0
loc 103
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like src.pytest_benchmark.TableResults.display() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
from __future__ import division
2
from __future__ import print_function
3
4
import operator
5
import sys
6
from math import isinf
7
8
from .utils import report_progress
9
from .utils import time_unit
10
11
NUMBER_FMT = "{0:,.4f}" if sys.version_info[:2] > (2, 6) else "{0:.4f}"
12
ALIGNED_NUMBER_FMT = "{0:>{1},.4f}{2:<{3}}" if sys.version_info[:2] > (2, 6) else "{0:>{1}.4f}{2:<{3}}"
13
14
15
class TableResults(object):
16
    def __init__(self, columns, sort, histogram, name_format, logger):
17
        self.columns = columns
18
        self.sort = sort
19
        self.histogram = histogram
20
        self.name_format = name_format
21
        self.logger = logger
22
23
    def display(self, tr, groups, progress_reporter=report_progress):
24
        tr.write_line("")
25
        tr.rewrite("Computing stats ...", black=True, bold=True)
26
        for line, (group, benchmarks) in progress_reporter(groups, tr, "Computing stats ... group {pos}/{total}"):
27
            benchmarks = sorted(benchmarks, key=operator.itemgetter(self.sort))
28
            for bench in benchmarks:
29
                bench["name"] = self.name_format(bench)
30
31
            worst = {}
32
            best = {}
33
            solo = len(benchmarks) == 1
34
            for line, prop in progress_reporter(("min", "max", "mean", "median", "iqr", "stddev"),
35
                                                tr, "{line}: {value}", line=line):
36
                worst[prop] = max(bench[prop] for _, bench in progress_reporter(
37
                    benchmarks, tr, "{line} ({pos}/{total})", line=line))
38
                best[prop] = min(bench[prop] for _, bench in progress_reporter(
39
                    benchmarks, tr, "{line} ({pos}/{total})", line=line))
40
            for line, prop in progress_reporter(("outliers", "rounds", "iterations"), tr, "{line}: {value}", line=line):
41
                worst[prop] = max(benchmark[prop] for _, benchmark in progress_reporter(
42
                    benchmarks, tr, "{line} ({pos}/{total})", line=line))
43
44
            time_unit_key = self.sort
45
            if self.sort in ("name", "fullname"):
46
                time_unit_key = "min"
47
            unit, adjustment = time_unit(best.get(self.sort, benchmarks[0][time_unit_key]))
48
            labels = {
49
                "name": "Name (time in {0}s)".format(unit),
50
                "min": "Min",
51
                "max": "Max",
52
                "mean": "Mean",
53
                "stddev": "StdDev",
54
                "rounds": "Rounds",
55
                "iterations": "Iterations",
56
                "iqr": "IQR",
57
                "median": "Median",
58
                "outliers": "Outliers(*)",
59
            }
60
            widths = {
61
                "name": 3 + max(len(labels["name"]), max(len(benchmark["name"]) for benchmark in benchmarks)),
62
                "rounds": 2 + max(len(labels["rounds"]), len(str(worst["rounds"]))),
63
                "iterations": 2 + max(len(labels["iterations"]), len(str(worst["iterations"]))),
64
                "outliers": 2 + max(len(labels["outliers"]), len(str(worst["outliers"]))),
65
            }
66
            for prop in "min", "max", "mean", "stddev", "median", "iqr":
67
                widths[prop] = 2 + max(len(labels[prop]), max(
68
                    len(NUMBER_FMT.format(bench[prop] * adjustment))
69
                    for bench in benchmarks
70
                ))
71
72
            rpadding = 0 if solo else 10
73
            labels_line = labels["name"].ljust(widths["name"]) + "".join(
74
                labels[prop].rjust(widths[prop]) + (
75
                    " " * rpadding
76
                    if prop not in ["outliers", "rounds", "iterations"]
77
                    else ""
78
                )
79
                for prop in self.columns
80
            )
81
            tr.rewrite("")
82
            tr.write_line(
83
                " benchmark{name}: {count} tests ".format(
84
                    count=len(benchmarks),
85
                    name="" if group is None else " {0!r}".format(group),
86
                ).center(len(labels_line), "-"),
87
                yellow=True,
88
            )
89
            tr.write_line(labels_line)
90
            tr.write_line("-" * len(labels_line), yellow=True)
91
92
            for bench in benchmarks:
93
                has_error = bench.get("has_error")
94
                tr.write(bench["name"].ljust(widths["name"]), red=has_error, invert=has_error)
95
                for prop in self.columns:
96
                    if prop in ("min", "max", "mean", "stddev", "median", "iqr"):
97
                        tr.write(
98
                            ALIGNED_NUMBER_FMT.format(
99
                                bench[prop] * adjustment,
100
                                widths[prop],
101
                                compute_baseline_scale(best[prop], bench[prop], rpadding),
102
                                rpadding
103
                            ),
104
                            green=not solo and bench[prop] == best.get(prop),
105
                            red=not solo and bench[prop] == worst.get(prop),
106
                            bold=True,
107
                        )
108
                    else:
109
                        tr.write("{0:>{1}}".format(bench[prop], widths[prop]))
110
                tr.write("\n")
111
            tr.write_line("-" * len(labels_line), yellow=True)
112
            tr.write_line("")
113
            if self.histogram:
114
                from .histogram import make_histogram
115
                print(["{0[name]}".format(row) for row in benchmarks])
116
                if len(benchmarks) > 75:
117
                    self.logger.warn("BENCHMARK-H1",
118
                                     "Group {0!r} has too many benchmarks. Only plotting 50 benchmarks.".format(group))
119
                    benchmarks = benchmarks[:75]
120
121
                output_file = make_histogram(self.histogram, group, benchmarks, unit, adjustment)
122
123
                self.logger.info("Generated histogram: {0}".format(output_file), bold=True)
124
125
        tr.write_line("(*) Outliers: 1 Standard Deviation from Mean; "
126
                      "1.5 IQR (InterQuartile Range) from 1st Quartile and 3rd Quartile.")
127
128
129
def compute_baseline_scale(baseline, value, width):
130
    if not width:
131
        return ""
132
    if value == baseline:
133
        return " (1.0)".ljust(width)
134
135
    scale = abs(value / baseline) if baseline else float("inf")
136
    if scale > 1000:
137
        if isinf(scale):
138
            return " (inf)".ljust(width)
139
        else:
140
            return " (>1000.0)".ljust(width)
141
    else:
142
        return " ({0:.2f})".format(scale).ljust(width)
143