How to use Symfony’s Stopwatch component to measure performance?

To use Symfony’s Stopwatch component to measure performance, you can follow these steps:

  1. Install symfony/stopwatch package via composer:
composer require symfony/stopwatch
  1. Create a Stopwatch instance in your code:
use Symfony\Component\Stopwatch\Stopwatch; $stopwatch = new Stopwatch();
  1. Start the stopwatch to begin measuring time:
$stopwatch->start('task_name');
  1. Perform the code or task you want to measure the performance of.

  2. Stop the stopwatch to end measuring time:

$event = $stopwatch->stop('task_name');
  1. You can now access information about the duration of the task:
$duration = $event->getDuration(); // in milliseconds echo 'Task duration: '.$duration.'ms';
  1. You can also access more detailed information about the task:
$periods = $event->getPeriods(); foreach ($periods as $index => $period) { echo 'Period '.$index.': '.$period->getDuration().'ms<br>'; }

By following these steps, you can effectively use Symfony’s Stopwatch component to measure the performance of your code and tasks.