The Stopwatch Component

    Note

    If you install this component outside of a Symfony application, you mustrequire the file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

    The Stopwatch component provides a consistent way to measure executiontime of certain parts of code so that you don't constantly have to parsemicrotime by yourself. Instead, use the class:

    1. use Symfony\Component\Stopwatch\Stopwatch;
    2.  
    3. $stopwatch = new Stopwatch();
    4. // starts event named 'eventName'
    5. $stopwatch->start('eventName');
    6. // ... some code goes here

    The StopwatchEvent object can be retrievedfrom the ,,lap() and methods.The latter should be used when you need to retrieve the duration of an eventwhile it is still running.

    Tip

    1. $stopwatch = new Stopwatch(true);

    The stopwatch can be reset to its original state at any given time with thereset() method, which deletesall the data measured so far.

    You can also provide a category name to an event:

    You can consider categories as a way of tagging events. For example, theSymfony Profiler tool uses categories to nicely color-code different events.

    Tip

    Read to learn more aboutintegrating the Stopwatch component into the Symfony profiler.

    As you know from the real world, all stopwatches come with two buttons:one to start and stop the stopwatch, and another to measure the lap time.This is exactly what the lap()method does:

    1. $stopwatch = new Stopwatch();
    2. // starts event named 'foo'
    3. $stopwatch->start('foo');
    4. // ... some code goes here
    5. $stopwatch->lap('foo');
    6. // ... some code goes here
    7. $stopwatch->lap('foo');
    8. // ... some other code goes here
    9. $event = $stopwatch->stop('foo');

    Lap information is stored as "periods" within the event. To get lap informationcall:

      In addition to periods, you can get other useful information from the event object.For example:

      Sections are a way to logically split the timeline into groups. You can seehow Symfony uses sections to nicely visualize the framework lifecycle in theSymfony Profiler tool. Here is a basic usage example using sections:

      1. $stopwatch = new Stopwatch();
      2.  
      3. $stopwatch->openSection();
      4. $stopwatch->start('parsing_config_file', 'filesystem_operations');
      5. $stopwatch->stopSection('routing');
      6.  
      7. $events = $stopwatch->getSectionEvents('routing');

      You can reopen a closed section by calling the method and specifying the id of the section to be reopened:

      1. $stopwatch->openSection('routing');
      2. $stopwatch->start('building_config_tree');
      3. $stopwatch->stopSection('routing');