Completed
Push — develop ( fe1195...b733eb )
by Alec
05:48
created

Benchmark::nonVerboseRun()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 3
nop 0
dl 0
loc 17
ccs 12
cts 12
cp 1
crap 3
rs 9.9
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A Benchmark::prepareResult() 0 10 2
1
<?php
2
/**
3
 * User: alec
4
 * Date: 29.11.18
5
 * Time: 11:04
6
 */
7
8
namespace AlecRabbit\Tools;
9
10
use AlecRabbit\Rewindable;
11
use AlecRabbit\Tools\Contracts\BenchmarkInterface;
12
use AlecRabbit\Tools\Internal\BenchmarkFunction;
13
use AlecRabbit\Tools\Reports\Contracts\ReportableInterface;
14
use AlecRabbit\Tools\Reports\Factory;
15
use AlecRabbit\Tools\Reports\Traits\Reportable;
16
use AlecRabbit\Tools\Traits\BenchmarkFields;
17
use function AlecRabbit\brackets;
18
use function AlecRabbit\typeOf;
19
20
class Benchmark implements BenchmarkInterface, ReportableInterface
21
{
22
    protected const PG_WIDTH = 60;
23
24
    use BenchmarkFields, Reportable;
25
26
    /** @var int */
27
    private $namingIndex = 0;
28
    /** @var Rewindable */
29
    private $rewindable;
30
    /** @var int */
31
    private $iterations = 0;
32
    /** @var null|string */
33
    private $comment;
34
    /** @var bool */
35
    private $verbose = false;
36
    /** @var bool */
37
    private $errorState = false;
38
    /** @var int */
39
    private $dots = 0;
40
41
    /**
42
     * Benchmark constructor.
43
     * @param int $iterations
44
     */
45 4
    public function __construct(int $iterations = 1000)
46
    {
47 4
        $this->iterations = $iterations;
48 4
        $this->rewindable =
49 4
            new Rewindable(
50
                function (int $iterations, int $i = 1): \Generator {
51 1
                    while ($i <= $iterations) {
52 1
                        yield $i++;
53
                    }
54 4
                },
55 4
                $iterations
56
            );
57 4
        $this->profiler = new Profiler();
58 4
    }
59
60
    /**
61
     * Launch benchmarking
62
     * @param bool $report
63
     */
64 1
    public function run(bool $report = false): void
65
    {
66 1
        if ($this->verbose) {
67
            echo
68
            sprintf(
69
                'Running benchmarks(%s):',
70
                $this->iterations
71
            );
72
            echo PHP_EOL;
73
        }
74 1
        $this->execute();
75 1
        echo PHP_EOL;
76 1
        echo PHP_EOL;
77
78 1
        if ($report) {
79
            echo (string)$this->getReport();
80
            echo PHP_EOL;
81
        }
82 1
    }
83
84
    /**
85
     * Launch benchmarking in verbose mode
86
     */
87 1
    private function execute(): void
88
    {
89
        /** @var  BenchmarkFunction $f */
90 1
        foreach ($this->functions as $name => $f) {
91 1
            $function = $f->getFunction();
92 1
            $args = $f->getArgs();
93 1
            $this->prepareResult($f, $function, $args);
94 1
            $timer = $this->profiler->timer($name);
95 1
            if ($this->errorState) {
96
                $this->errorState = false;
97
                $timer->check();
98
                continue;
99
            }
100 1
            foreach ($this->rewindable as $iteration) {
101 1
                $this->bench($timer, $function, $args, $iteration);
102
            }
103 1
            $this->profiler->counter()->bump();
104
        }
105 1
    }
106
107
    /**
108
     * @param BenchmarkFunction $f
109
     * @param callable $function
110
     * @param array $args
111
     */
112 1
    private function prepareResult(BenchmarkFunction $f, callable $function, array $args): void
113
    {
114
        try {
115 1
            $result = $function(...$args);
116
        } catch (\Throwable $e) {
117
            $this->errorState = true;
118
            $result = brackets(typeOf($e)) . ': ' . $e->getMessage();
119
            $this->exceptionMessages[$f->getIndexedName()] = $result;
120
        }
121 1
        $f->setResult($result);
122 1
    }
123
124
    /**
125
     * @param Timer $timer
126
     * @param callable $function
127
     * @param array $args
128
     * @param int $iteration
129
     */
130 1
    private function bench(Timer $timer, callable $function, array $args, int $iteration): void
131
    {
132 1
        $timer->start();
133 1
        $function(...$args);
134 1
        $timer->check($iteration);
135 1
        $this->progress();
136 1
    }
137
138 1
    private function progress(): void
139
    {
140 1
        if ($this->verbose && 1 === ++$this->totalIterations % 5000) {
141
            echo '.';
142
            if (++$this->dots > static::PG_WIDTH) {
143
                echo PHP_EOL;
144
                $this->dots = 0;
145
            }
146
        }
147 1
    }
148
149
    /**
150
     * @return Benchmark
151
     */
152
    public function verbose(): self
153
    {
154
        $this->verbose = true;
155
        return $this;
156
    }
157
158
    /**
159
     * @return Benchmark
160
     */
161
    public function color(): self
162
    {
163
        Factory::setColour(true);
164
        return $this;
165
    }
166
167
    /**
168
     * @param callable $func
169
     * @param mixed ...$args
170
     */
171 2
    public function addFunction($func, ...$args): void
172
    {
173 2
        if (!\is_callable($func, false, $name)) {
174 1
            throw new \InvalidArgumentException(
175 1
                sprintf(
176 1
                    '\'%s\' is NOT callable. Function must be callable. Type of "%s" provided instead.',
177 1
                    $name,
178 1
                    typeOf($func)
179
                )
180
            );
181
        }
182 1
        $function = new BenchmarkFunction($func, $name, $this->namingIndex++, $args, $this->comment);
183 1
        $this->comment = null;
184
185 1
        $this->functions[$function->getEnumeratedName()] = $function;
186 1
    }
187
188
    /**
189
     * @param string $name
190
     * @return Benchmark
191
     */
192 2
    public function withComment(string $name): self
193
    {
194 2
        $this->comment = $name;
195 2
        return $this;
196
    }
197
198
    /**
199
     * @return Benchmark
200
     */
201
    public function returnResults(): self
202
    {
203
        $this->withResults = true;
204
        return $this;
205
    }
206
207
    /**
208
     * @return string
209
     */
210
    public function elapsed(): string
211
    {
212
        $theme = Factory::getThemeObject();
213
        return
214
            sprintf(
215
                'Done in: %s',
216
                $theme->yellow($this->getProfiler()->timer()->elapsed())
217
            );
218
    }
219
220
    /**
221
     * {@inheritdoc}
222
     */
223 2
    protected function prepareForReport(): void
224
    {
225 2
        $this->getProfiler()->getReport();
226 2
    }
227
}
228