Failed Conditions
Pull Request — master (#8)
by Donatas
17:58 queued 08:01
created

StepTimeLogger::executionInformationGenerator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 2
nc 2
nop 0
1
<?php
2
3
namespace Bex\Behat\StepTimeLoggerExtension\Service;
4
5
class StepTimeLogger
6
{
7
    /**
8
     * @var float
9
     */
10
    private $lastStepStartTime;
11
12
    /**
13
     * @var array
14
     */
15
    private $calledSteps = [];
16
17
    /**
18
     * @var array
19
     */
20
    private $executionTimes = [];
21
22
    /**
23
     * @param string $stepName
24
     */
25
    public function logStepStarted($stepName)
26
    {
27
        $this->calledSteps[] = $stepName;
28
        $this->lastStepStartTime = microtime(true);
29
    }
30
31
    /**
32
     * @param string $stepName
33
     */
34
    public function logStepFinished($stepName)
35
    {
36
        $this->executionTimes[$stepName][] = round(microtime(true) - $this->lastStepStartTime, 5);
37
    }
38
39
    /**
40
     * @return void
41
     */
42
    public function clearLogs()
43
    {
44
        $this->calledSteps = [];
45
        $this->executionTimes = [];
46
    }
47
48
    /**
49
     * @return array
50
     */
51
    public function getCalledCounts()
52
    {
53
        return array_count_values($this->calledSteps);
54
    }
55
56
    /**
57
     * @return array
58
     */
59
    public function getAvegrageExecutionTimes()
60
    {
61
        $avgTimes = [];
62
63
        foreach ($this->executionTimes as $stepName => $executionTimes) {
64
            $avgTimes[$stepName] = array_sum($executionTimes) / count($executionTimes);
65
        }
66
67
        arsort($avgTimes);
68
69
        return $avgTimes;
70
    }
71
72
    /**
73
     * @return \Generator
74
     */
75
    public function executionInformationGenerator()
76
    {
77
        foreach ($this->executionTimes as $stepName => $executionTimes) {
78
            $totalExecutions = count($executionTimes);
79
            $avgExecutionTime = array_sum($executionTimes) / $totalExecutions;
80
81
            yield $stepName => [
82
                'avg_execution_time' => $avgExecutionTime,
83
                'total_executions' => $totalExecutions,
84
                'total_cost' => $avgExecutionTime * $totalExecutions
85
            ];
86
        }
87
    }
88
}
89