From af00d8deabf04bc218f7004986e2b4ba4132b9bb Mon Sep 17 00:00:00 2001 From: Timo Bakx Date: Tue, 29 Oct 2019 21:16:34 +0100 Subject: [PATCH] [Stopwatch] Fixed bug in getDuration when counting multiple ongoing periods --- .../Component/Stopwatch/StopwatchEvent.php | 8 +++----- .../Stopwatch/Tests/StopwatchEventTest.php | 19 ++++++++++++++++++- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/Symfony/Component/Stopwatch/StopwatchEvent.php b/src/Symfony/Component/Stopwatch/StopwatchEvent.php index bc8c6b5f47b7..158c7a7dcaf7 100644 --- a/src/Symfony/Component/Stopwatch/StopwatchEvent.php +++ b/src/Symfony/Component/Stopwatch/StopwatchEvent.php @@ -177,12 +177,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; diff --git a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php index 86a02b153591..bf63a44874e3 100644 --- a/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php +++ b/src/Symfony/Component/Stopwatch/Tests/StopwatchEventTest.php @@ -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()