Passed
Push — develop ( 0a2c3f...8e5858 )
by Alec
03:05
created

Benchmark::setShowReturns()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace AlecRabbit\Tools;
4
5
use AlecRabbit\Accessories\MemoryUsage;
6
use AlecRabbit\Accessories\Rewindable;
7
use AlecRabbit\Tools\Contracts\BenchmarkInterface;
8
use AlecRabbit\Tools\Contracts\Strings;
9
use AlecRabbit\Tools\Internal\BenchmarkFunction;
10
use AlecRabbit\Tools\Reports\BenchmarkReport;
11
use AlecRabbit\Tools\Traits\BenchmarkFields;
12
use function AlecRabbit\typeOf;
13
14
class Benchmark extends Reportable implements BenchmarkInterface, Strings
15
{
16
    use BenchmarkFields;
17
18
    public const MIN_ITERATIONS = 100;
19
    public const DEFAULT_STEPS = 100;
20
    public const CLOSURE_NAME = 'λ';
21
22
    /** @var int */
23
    protected $advanceSteps = self::DEFAULT_STEPS;
24
    /** @var Rewindable */
25
    protected $rewindable;
26
    /** @var int */
27
    protected $iterations;
28
    /** @var null|string */
29
    protected $comment;
30
    /** @var string|null */
31
    protected $humanReadableName;
32
    /** @var int */
33
    protected $totalIterations = 0;
34
    /** @var null|callable */
35
    protected $onStart;
36
    /** @var null|callable */
37
    protected $onAdvance;
38
    /** @var null|callable */
39
    protected $onFinish;
40
    /** @var int */
41
    protected $advanceStep = 0;
42
    /** @var \Closure */
43
    protected $iterationNumberGenerator;
44
    /** @var bool */
45
    protected $launched = false;
46
    /** @var int */
47
    protected $functionIndex = 1;
48
49
    /**
50
     * Benchmark constructor.
51
     * @param int $iterations
52
     * @throws \Exception
53
     */
54 16
    public function __construct(?int $iterations = null)
55
    {
56 16
        $this->iterations = $this->refineIterations($iterations);
57
58 16
        $this->iterationNumberGenerator =
59
            function (int $iterations, int $i = 1): \Generator {
60 13
                while ($i <= $iterations) {
61 13
                    yield $i++;
62
                }
63 13
            };
64
65 16
        $this->timer = new Timer(); // Timer to count benchmark process total time
66 16
        $this->initialize();
67 16
    }
68
69 16
    protected function refineIterations(?int $iterations): int
70
    {
71 16
        $iterations = $iterations ?? self::MIN_ITERATIONS;
72 16
        $this->assertIterations($iterations);
73 16
        return $iterations;
74
    }
75
76
    /**
77
     * @param int $iterations
78
     */
79 16
    protected function assertIterations(int $iterations): void
80
    {
81 16
        if ($iterations < self::MIN_ITERATIONS) {
82 1
            throw new \RuntimeException(
83
                __CLASS__ .
84
                ': Number of Iterations should be greater then ' .
85 1
                self::MIN_ITERATIONS
86
            );
87
        }
88 16
    }
89
90
    /**
91
     * Resets Benchmark object clear
92
     * @throws \Exception
93
     */
94 16
    protected function initialize(): void
95
    {
96 16
        unset($this->functions, $this->humanReadableName, $this->rewindable, $this->memoryUsageReport);
97
98 16
        $this->humanReadableName = null;
99 16
        $this->rewindable =
100 16
            new Rewindable(
101 16
                $this->iterationNumberGenerator,
102 16
                $this->iterations
103
            );
104 16
        $this->functions = [];
105 16
        $this->added = new SimpleCounter('added');
106 16
        $this->benchmarked = new SimpleCounter('benchmarked');
107 16
        $this->memoryUsageReport = MemoryUsage::report();
108 16
        $this->doneIterations = 0;
109 16
        $this->totalIterations = 0;
110 16
        $this->report = (new BenchmarkReport())->buildOn($this);
111 16
    }
112
113
    /**
114
     * Resets Benchmark object clear
115
     * @throws \Exception
116
     */
117 1
    public function reset(): void
118
    {
119 1
        $this->initialize();
120 1
    }
121
122
    /**
123
     * @param callable|null $onStart
124
     * @param callable|null $onAdvance
125
     * @param callable|null $onFinish
126
     * @return Benchmark
127
     */
128 2
    public function showProgressBy(
129
        callable $onStart = null,
130
        callable $onAdvance = null,
131
        callable $onFinish = null
132
    ): Benchmark {
133 2
        $this->onStart = $onStart;
134 2
        $this->onAdvance = $onAdvance;
135 2
        $this->onFinish = $onFinish;
136 2
        return $this;
137
    }
138
139
    /**
140
     * @param mixed $func
141
     * @param mixed ...$args
142
     */
143 14
    public function addFunction($func, ...$args): void
144
    {
145 14
        if (!\is_callable($func, false, $name)) {
146 1
            throw new \InvalidArgumentException(
147 1
                sprintf(
148 1
                    '\'%s\' is NOT callable. Function must be callable. Type of "%s" provided instead.',
149
                    $name,
150 1
                    typeOf($func)
151
                )
152
            );
153
        }
154
        $function =
155 13
            new BenchmarkFunction(
156 13
                $func,
157 13
                $this->refineName($func, $name),
158 13
                $this->functionIndex++,
159
                $args,
160 13
                $this->comment,
161 13
                $this->humanReadableName
162
            );
163 13
        $function->setShowReturns($this->isShowReturns());
164 13
        $this->functions[$function->enumeratedName()] = $function;
165 13
        $this->humanReadableName = null;
166 13
        $this->comment = null;
167 13
        $this->added->bump();
168 13
        $this->totalIterations += $this->iterations;
169 13
    }
170
171
    /**
172
     * @param callable $func
173
     * @param string $name
174
     * @return string
175
     */
176 13
    protected function refineName($func, $name): string
177
    {
178 13
        if ($func instanceof \Closure) {
179 13
            $name = self::CLOSURE_NAME;
180
        }
181 13
        return $name;
182
    }
183
184
    /**
185
     * @param string $comment
186
     * @return Benchmark
187
     */
188 5
    public function withComment(string $comment): self
189
    {
190 5
        $this->comment = $comment;
191 5
        return $this;
192
    }
193
194
    /**
195
     * @param string $name
196
     * @return Benchmark
197
     */
198 4
    public function useName(string $name): self
199
    {
200 4
        $this->humanReadableName = $name;
201 4
        return $this;
202
    }
203
204
    /**
205
     * @return string
206
     * @throws \Exception
207
     */
208 4
    public function stat(): string
209
    {
210
        return
211 4
            sprintf(
212 4
                'Done in: %s%s%s',
213 4
                $this->getTimer()->elapsed(),
214 4
                PHP_EOL,
215 4
                (string)$this->memoryUsageReport
216
            );
217
    }
218
219
    /**
220
     * @return Benchmark
221
     */
222
    public function showReturns(): Benchmark
223
    {
224
        $this->setShowReturns(true);
225
        foreach ($this->functions as $function) {
226
            $function->setShowReturns($this->isShowReturns());
227
        }
228
        return $this;
229
    }
230
231
    /**
232
     * @param bool $showReturns
233
     */
234
    public function setShowReturns(bool $showReturns): void
235
    {
236
        $this->showReturns = $showReturns;
237
    }
238
239
    /** {@inheritdoc} */
240 14
    protected function meetConditions(): void
241
    {
242 14
        if ($this->isNotLaunched()) {
243 11
            $this->run();
244
        }
245 14
    }
246
247
    /**
248
     * @return bool
249
     */
250 14
    public function isNotLaunched(): bool
251
    {
252 14
        return !$this->isLaunched();
253
    }
254
255
    /**
256
     * @return bool
257
     */
258 14
    public function isLaunched(): bool
259
    {
260 14
        return $this->launched;
261
    }
262
263
    /**
264
     * Launch benchmarking
265
     */
266 14
    public function run(): self
267
    {
268 14
        $this->launched = true;
269 14
        if ($this->onStart) {
270 2
            ($this->onStart)();
271
        }
272 14
        $this->execute();
273 14
        if ($this->onFinish) {
274 2
            ($this->onFinish)();
275
        }
276 14
        $this->doneIterationsCombined += $this->doneIterations;
277 14
        return $this;
278
    }
279
280
    /**
281
     * Benchmarking
282
     */
283 14
    protected function execute(): void
284
    {
285
        /** @var  BenchmarkFunction $f */
286 14
        foreach ($this->functions as $f) {
287 13
            if (!$f->execute()) {
288 5
                $this->totalIterations -= $this->iterations;
289 5
                continue;
290
            }
291 13
            $this->advanceStep = (int)($this->totalIterations / $this->advanceSteps);
292 13
            $this->bench($f);
293 13
            $this->benchmarked->bump();
294
        }
295 14
    }
296
297
    /**
298
     * @param BenchmarkFunction $f
299
     */
300 13
    protected function bench(BenchmarkFunction $f): void
301
    {
302 13
        $timer = $f->getTimer();
303 13
        $function = $f->getCallable();
304 13
        $args = $f->getArgs();
305 13
        foreach ($this->rewindable as $iteration) {
306 13
            $start = microtime(true);
307
            /** @noinspection DisconnectedForeachInstructionInspection */
308 13
            $function(...$args);
309 13
            $stop = microtime(true);
310 13
            $timer->bounds($start, $stop, $iteration);
311
            /** @noinspection DisconnectedForeachInstructionInspection */
312 13
            $this->progress();
313
        }
314 13
    }
315
316 13
    protected function progress(): void
317
    {
318 13
        $this->doneIterations++;
319 13
        if ($this->onAdvance && 0 === $this->doneIterations % $this->advanceStep) {
320 2
            ($this->onAdvance)();
321
        }
322 13
    }
323
}
324