Completed
Push — develop ( b733eb...69cb61 )
by Alec
06:31
created

Benchmark::reset()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 1
nop 0
dl 0
loc 14
ccs 10
cts 10
cp 1
crap 2
rs 9.9666
c 0
b 0
f 0
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;
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 5
    public function __construct(int $iterations = 1000)
46
    {
47 5
        $this->iterations = $iterations;
48 5
        $this->reset();
49 5
    }
50
51
    /**
52
     * Resets Benchmark object clear
53
     */
54 5
    public function reset(): void
55
    {
56 5
        $this->functions = [];
57 5
        $this->rewindable =
58 5
            new Rewindable(
59
                function (int $iterations, int $i = 1): \Generator {
60 2
                    while ($i <= $iterations) {
61 2
                        yield $i++;
62
                    }
63 5
                },
64 5
                $this->iterations
65
            );
66 5
        $this->profiler = new Profiler();
67 5
        $this->resetReportObject();
68 5
    }
69
70
    /**
71
     * Launch benchmarking
72
     * @param bool $report
73
     */
74 2
    public function run(bool $report = false): void
75
    {
76 2
        if ($this->verbose) {
77
            echo
78 1
            sprintf(
79 1
                'Running benchmarks(%s):',
80 1
                $this->iterations
81
            );
82 1
            echo PHP_EOL;
83
        }
84 2
        $this->execute();
85 2
        echo PHP_EOL;
86 2
        echo PHP_EOL;
87
88 2
        if ($report) {
89 1
            echo (string)$this->getReport();
90 1
            echo PHP_EOL;
91
        }
92 2
    }
93
94
    /**
95
     * Launch benchmarking in verbose mode
96
     */
97 2
    private function execute(): void
98
    {
99 2
        dump($this->functions);
100
        /** @var  BenchmarkFunction $f */
101 2
        foreach ($this->functions as $name => $f) {
102 2
            $function = $f->getFunction();
103 2
            $args = $f->getArgs();
104 2
            $this->prepareResult($f, $function, $args);
105 2
            $timer = $this->profiler->timer($name);
106 2
            if ($this->errorState) {
107 1
                $this->errorState = false;
108 1
                $timer->check();
109 1
                continue;
110
            }
111 2
            foreach ($this->rewindable as $iteration) {
112 2
                $this->bench($timer, $function, $args, $iteration);
113
            }
114 2
            $this->profiler->counter()->bump();
115
        }
116 2
    }
117
118
    /**
119
     * @param BenchmarkFunction $f
120
     * @param callable $function
121
     * @param array $args
122
     */
123 2
    private function prepareResult(BenchmarkFunction $f, callable $function, array $args): void
124
    {
125
        try {
126 2
            $result = $function(...$args);
127 1
        } catch (\Throwable $e) {
128 1
            $this->errorState = true;
129 1
            $result = brackets(typeOf($e)) . ': ' . $e->getMessage();
130 1
            $this->exceptionMessages[$f->getIndexedName()] = $result;
131
        }
132 2
        $f->setResult($result);
133 2
    }
134
135
    /**
136
     * @param Timer $timer
137
     * @param callable $function
138
     * @param array $args
139
     * @param int $iteration
140
     */
141 2
    private function bench(Timer $timer, callable $function, array $args, int $iteration): void
142
    {
143 2
        $timer->start();
144 2
        $function(...$args);
145 2
        $timer->check($iteration);
146 2
        $this->progress();
147 2
    }
148
149 2
    private function progress(): void
150
    {
151 2
        if ($this->verbose && 1 === ++$this->totalIterations % 5000) {
152 1
            echo '.';
153 1
            if (++$this->dots > static::PG_WIDTH) {
154 1
                echo PHP_EOL;
155 1
                $this->dots = 0;
156
            }
157
        }
158 2
    }
159
160
    /**
161
     * @return Benchmark
162
     */
163 1
    public function verbose(): self
164
    {
165 1
        $this->verbose = true;
166 1
        return $this;
167
    }
168
169
    /**
170
     * @return Benchmark
171
     */
172 2
    public function color(): self
173
    {
174 2
        Factory::setColour(true);
175 2
        return $this;
176
    }
177
178
    /**
179
     * @param callable $func
180
     * @param mixed ...$args
181
     */
182 3
    public function addFunction($func, ...$args): void
183
    {
184 3
        if (!\is_callable($func, false, $name)) {
185 1
            throw new \InvalidArgumentException(
186 1
                sprintf(
187 1
                    '\'%s\' is NOT callable. Function must be callable. Type of "%s" provided instead.',
188 1
                    $name,
189 1
                    typeOf($func)
190
                )
191
            );
192
        }
193 2
        $function = new BenchmarkFunction($func, $name, $this->namingIndex++, $args, $this->comment);
194 2
        $this->functions[$function->getEnumeratedName()] = $function;
195 2
        $this->comment = null;
196 2
    }
197
198
    /**
199
     * @param string $name
200
     * @return Benchmark
201
     */
202 2
    public function withComment(string $name): self
203
    {
204 2
        $this->comment = $name;
205 2
        return $this;
206
    }
207
208
    /**
209
     * @return Benchmark
210
     */
211 1
    public function returnResults(): self
212
    {
213 1
        $this->withResults = true;
214 1
        return $this;
215
    }
216
217
    /**
218
     * @return string
219
     * @throws \Throwable
220
     */
221 1
    public function elapsed(): string
222
    {
223 1
        $theme = Factory::getThemedObject();
224
        return
225 1
            sprintf(
226 1
                'Done in: %s',
227 1
                $theme->yellow($this->getProfiler()->timer()->elapsed())
228
            );
229
    }
230
231
    /**
232
     * {@inheritdoc}
233
     */
234 3
    protected function prepareForReport(): void
235
    {
236 3
        $this->getProfiler()->getReport();
237 3
    }
238
}
239