Profiling Code With Symfony Stopwatch

You have probably, at some point, wanted to see how long a piece of code takes to execute. It is the most basic of profiling tasks when checking the efficiency of your code.

The easiest way to do this is by using PHP's microtime function. This gives the current Unix time as microseconds. If you do this at the start of the script and then at the end, you can calculate how long it took for it to run.

But it has some annoyances. First, you always have to remember to give it true as a parameter (so microtime(true)), otherwise it will return a string which will then give odd results later.

Next, you have to always remember which way around you have to do the calculation (its the end time minus the start time).

But the worst thing is if you want to track multiple times in the same script. Then you have to remember which variable is tracking what and which time is for what.

Symfony's Stopwatch is basically a wrapper around all of this and is really easy to use.


Like with the other components, it is very easy to install using Composer. Just include:


and the version (currently 3.3).

Then, where ever you want to use it, just include the class:

use Symfony\Component\Stopwatch\Stopwatch;

Basic Usage

So to use the stop watch is very simple:

$stopwatch = new Stopwatch();
foreach (range(1, 10) as $i) {
    sleep(rand(1, $i));
$event = $stopwatch->stop('myloop');

As you can see, I ran some code in between the start and stop. I just did something quick and simple to make some time pass. The $event now has a bunch of information in it. So I can run:


To get the time it took to run, which when I ran the above was:


This is in milliseconds (so divide by 1000 to get the seconds).

You can also do


which gives you the amount of memory in bytes that was used (my script used about 2097152 bytes or 2Mb).

So you can see that it is very simple to use. As you can see, you could have multiple stopwatches happening at once if you give them different names.

You can also do 'laps' with your stopwatch. For example, I added a lap in my foreach loop:

foreach (range(1, 10) as $i) {
    sleep(rand(1, $i));
    if ($i == 5) {

I can then access each period using:

$periods = $event->getPeriods();

Then you can access similar function as the event one for each period:

foreach ($periods as $period) { var_dump($period->getDuration()); }

So this gave me:


I could still access the total duration by doing $event->getDuration(); which then gave me the total of the above int(38005).


This should get you started on making it very easy to do basic profiling of your code. There are a couple of other ways that you can organise your stopwatches that I skipped and the documentation covers all of them (as well as what is covered here).

© 2012-2017