Skip to content

Commit

Permalink
bug #34181 [Stopwatch] Fixed bug in getDuration when counting multipl…
Browse files Browse the repository at this point in the history
…e ongoing periods (TimoBakx)

This PR was merged into the 3.4 branch.

Discussion
----------

[Stopwatch] Fixed bug in getDuration when counting multiple ongoing periods

| Q             | A
| ------------- | ---
| Branch?       | 3.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #34087
| License       | MIT
| Doc PR        | N/A

When running multiple periods in StopwatchEvent (start multiple times and not stop them all), the getDuration() method would return unexpected values.

This was because at every stop, the last entry in the `started` array was removed, while the `getDuration` method was still expecting all the started events to still be there.

Now, when calling `getDuration`, the duration of all the finished periods are added together with the unfinished counts.

Commits
-------

af00d8d [Stopwatch] Fixed bug in getDuration when counting multiple ongoing periods
  • Loading branch information
fabpot committed Nov 3, 2019
2 parents 767b265 + af00d8d commit 9162892
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
8 changes: 3 additions & 5 deletions src/Symfony/Component/Stopwatch/StopwatchEvent.php
Expand Up @@ -185,12 +185,10 @@ public function getEndTime()
public function getDuration()
{
$periods = $this->periods;
$stopped = \count($periods);
$left = \count($this->started) - $stopped;
$left = \count($this->started);

for ($i = 0; $i < $left; ++$i) {
$index = $stopped + $i;
$periods[] = new StopwatchPeriod($this->started[$index], $this->getNow(), $this->morePrecision);
for ($i = $left - 1; $i >= 0; --$i) {
$periods[] = new StopwatchPeriod($this->started[$i], $this->getNow(), $this->morePrecision);
}

$total = 0;
Expand Down
19 changes: 18 additions & 1 deletion src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php
Expand Up @@ -99,8 +99,25 @@ public function testDurationBeforeStop()
$event->stop();
usleep(50000);
$event->start();
usleep(100000);
$this->assertEqualsWithDelta(100, $event->getDuration(), self::DELTA);
usleep(100000);
$this->assertEqualsWithDelta(200, $event->getDuration(), self::DELTA);
}

public function testDurationWithMultipleStarts()
{
$event = new StopwatchEvent(microtime(true) * 1000);
$event->start();
usleep(100000);
$event->start();
usleep(100000);
$this->assertEqualsWithDelta(300, $event->getDuration(), self::DELTA);
$event->stop();
$this->assertEqualsWithDelta(300, $event->getDuration(), self::DELTA);
usleep(100000);
$this->assertEqualsWithDelta(400, $event->getDuration(), self::DELTA);
$event->stop();
$this->assertEqualsWithDelta(400, $event->getDuration(), self::DELTA);
}

public function testStopWithoutStart()
Expand Down

0 comments on commit 9162892

Please sign in to comment.