Completed
Push — master ( 0accbd...f9f913 )
by Alec
03:04
created

Benchmark::__construct()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 1
nop 1
dl 0
loc 13
ccs 8
cts 8
cp 1
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 18
    public function __construct(?int $iterations = null)
55
    {
56 18
        $this->iterations = $this->refineIterations($iterations);
57
58 18
        $this->iterationNumberGenerator =
59
            function (int $iterations, int $i = 1): \Generator {
60 14
                while ($i <= $iterations) {
61 14
                    yield $i++;
62
                }
63 14
            };
64
65 18
        $this->timer = new Timer(); // Timer to count benchmark process total time
66 18
        $this->initialize();
67 18
    }
68
69 18
    protected function refineIterations(?int $iterations): int
70
    {
71 18
        $iterations = $iterations ?? self::MIN_ITERATIONS;
72 18
        $this->assertIterations($iterations);
73 18
        return $iterations;
74
    }
75
76
    /**
77
     * @param int $iterations
78
     */
79 18
    protected function assertIterations(int $iterations): void
80
    {
81 18
        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 18
    }
89
90
    /**
91
     * Resets Benchmark object clear
92
     * @throws \Exception
93
     */
94 18
    protected function initialize(): void
95
    {
96 18
        unset($this->functions, $this->humanReadableName, $this->rewindable, $this->memoryUsageReport);
97
98 18
        $this->humanReadableName = null;
99 18
        $this->rewindable =
100 18
            new Rewindable(
101 18
                $this->iterationNumberGenerator,
102 18
                $this->iterations
103
            );
104 18
        $this->functions = [];
105 18
        $this->added = new SimpleCounter('added');
106 18
        $this->benchmarked = new SimpleCounter('benchmarked');
107 18
        $this->memoryUsageReport = MemoryUsage::report();
108 18
        $this->doneIterations = 0;
109 18
        $this->totalIterations = 0;
110 18
        $this->report = (new BenchmarkReport())->buildOn($this);
111 18
    }
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 15
    public function addFunction($func, ...$args): void
144
    {
145 15
        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 14
            new BenchmarkFunction(
156 14
                $func,
157 14
                $this->refineName($func, $name),
158 14
                $this->functionIndex++,
159
                $args,
160 14
                $this->comment,
161 14
                $this->humanReadableName
162
            );
163 14
        $function->setShowReturns($this->isShowReturns());
164 14
        $this->functions[$function->enumeratedName()] = $function;
165 14
        $this->humanReadableName = null;
166 14
        $this->comment = null;
167 14
        $this->added->bump();
168 14
        $this->totalIterations += $this->iterations;
169 14
    }
170
171
    /**
172
     * @param callable $func
173
     * @param string $name
174
     * @return string
175
     */
176 14
    protected function refineName($func, $name): string
177
    {
178 14
        if ($func instanceof \Closure) {
179 14
            $name = self::CLOSURE_NAME;
180
        }
181 14
        return $name;
182
    }
183
184
    /**
185
     * @param string $comment
186
     * @return Benchmark
187
     */
188 6
    public function withComment(string $comment): self
189
    {
190 6
        $this->comment = $comment;
191 6
        return $this;
192
    }
193
194
    /**
195
     * @param string $name
196
     * @return Benchmark
197
     */
198 5
    public function useName(string $name): self
199
    {
200 5
        $this->humanReadableName = $name;
201 5
        return $this;
202
    }
203
204
    /**
205
     * @return string
206
     * @throws \Exception
207
     */
208 5
    public function stat(): string
209
    {
210
        return
211 5
            sprintf(
212 5
                'Done in: %s%s%s',
213 5
                $this->getTimer()->elapsed(),
214 5
                PHP_EOL,
215 5
                (string)$this->memoryUsageReport
216
            );
217
    }
218
219
    /**
220
     * @return Benchmark
221
     */
222 1
    public function showReturns(): Benchmark
223
    {
224 1
        $this->setShowReturns(true);
225 1
        foreach ($this->functions as $function) {
226 1
            $function->setShowReturns($this->isShowReturns());
227
        }
228 1
        return $this;
229
    }
230
231
    /**
232
     * @param bool $showReturns
233
     */
234 1
    public function setShowReturns(bool $showReturns): void
235
    {
236 1
        $this->showReturns = $showReturns;
237 1
    }
238
239
    /** {@inheritdoc} */
240 15
    protected function meetConditions(): void
241
    {
242 15
        if ($this->isNotLaunched()) {
243 12
            $this->run();
244
        }
245 15
    }
246
247
    /**
248
     * @return bool
249
     */
250 15
    public function isNotLaunched(): bool
251
    {
252 15
        return !$this->isLaunched();
253
    }
254
255
    /**
256
     * @return bool
257
     */
258 15
    public function isLaunched(): bool
259
    {
260 15
        return $this->launched;
261
    }
262
263
    /**
264
     * Launch benchmarking
265
     */
266 15
    public function run(): self
267
    {
268 15
        $this->launched = true;
269 15
        if ($this->onStart) {
270 2
            ($this->onStart)();
271
        }
272 15
        $this->execute();
273 15
        if ($this->onFinish) {
274 2
            ($this->onFinish)();
275
        }
276 15
        $this->doneIterationsCombined += $this->doneIterations;
277 15
        return $this;
278
    }
279
280
    /**
281
     * Benchmarking
282
     */
283 15
    protected function execute(): void
284
    {
285
        /** @var  BenchmarkFunction $f */
286 15
        foreach ($this->functions as $f) {
287 14
            if (!$f->execute()) {
288 6
                $this->totalIterations -= $this->iterations;
289 6
                continue;
290
            }
291 14
            $this->advanceStep = (int)($this->totalIterations / $this->advanceSteps);
292 14
            $this->bench($f);
293 14
            $this->benchmarked->bump();
294
        }
295 15
    }
296
297
    /**
298
     * @param BenchmarkFunction $f
299
     */
300 14
    protected function bench(BenchmarkFunction $f): void
301
    {
302 14
        $timer = $f->getTimer();
303 14
        $function = $f->getCallable();
304 14
        $args = $f->getArgs();
305 14
        foreach ($this->rewindable as $iteration) {
306 14
            $start = microtime(true);
307
            /** @noinspection DisconnectedForeachInstructionInspection */
308 14
            $function(...$args);
309 14
            $stop = microtime(true);
310 14
            $timer->bounds($start, $stop, $iteration);
311
            /** @noinspection DisconnectedForeachInstructionInspection */
312 14
            $this->progress();
313
        }
314 14
    }
315
316 14
    protected function progress(): void
317
    {
318 14
        $this->doneIterations++;
319 14
        if ($this->onAdvance && 0 === $this->doneIterations % $this->advanceStep) {
320 2
            ($this->onAdvance)();
321
        }
322 14
    }
323
}
324