How To Use Profiler In CLI Command

Following our previous post about adding a progress bar in a cli command, in this post we will find out how we can use magento profiler getting statistics about the execution of our command. Let's have look on that!

In this post we will use as a base the previous module we have created. So firstly we will define our CLI command in the di.xml and also configure the command's name via constructor $name argument like you see below.

Afterwards in our class ProfilerCommand we created the execute function that will be called from our CLI command. So instead of the ProgressBarFactory class we injected in our last post, we will inject the StatFactory class. So as you can see below, we create an instance of the class StatFactory and then we call it's function called start with same parameters needed, like a timer id, the time, the real size of memory allocated from system and the memory used by emalloc(). For the timer id we set a string called 'magevision_blog64_profiler', for the time we use the microtime(true) function as parameter which returns the current unix timestamp with microseconds, for the real memory we use the function memory_get_usage(true) as parameter which returns the amount of memory allocated to PHP from system and for emalloc memory we use again the function memory_get_usage() but without the parameter set as we want to get only the memory used by emalloc().

After calling the start() function we add the functionality of our command and then we call the function stop() with exactly the same parameters we use when we call the start() function. Now to get the statistics we need to call the function get() pass as parameter our timer id.

The results of this function is an array of the data we need to display. Below you can see the output in the terminal when calling our command php bin/magento magevision:blog64:profiler.

The full example as extension can be found here.

Feel free to share this post and ask your questions in the comments below.

Till next time!