How can I measure the speed of code written in PHP?

I've made a simple timing class, maybe it's useful to someone:

class TimingHelper {

    private $start;

    public function __construct() {
        $this->start = microtime(true);
    }

    public function start() {
        $this->start = microtime(true);
    }

    public function segs() {
        return microtime(true) - $this->start;
    }

    public function time() {
        $segs = $this->segs();
        $days = floor($segs / 86400);
        $segs -= $days * 86400;
        $hours = floor($segs / 3600);
        $segs -= $hours * 3600;
        $mins = floor($segs / 60);
        $segs -= $mins * 60;
        $microsegs = ($segs - floor($segs)) * 1000;
        $segs = floor($segs);

        return 
            (empty($days) ? "" : $days . "d ") . 
            (empty($hours) ? "" : $hours . "h ") . 
            (empty($mins) ? "" : $mins . "m ") . 
            $segs . "s " .
            $microsegs . "ms";
    }

}

Use:

$th = new TimingHelper();
<..code being mesured..>
echo $th->time();
$th->start(); // if it's the case
<..code being mesured..>
echo $th->time();

// result: 4d 17h 34m 57s 0.00095367431640625ms 

For quick stuff I do this (in PHP):

$startTime = microtime(true);
doTask(); // whatever you want to time
echo "Time:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";

You can also use a profiler like http://xdebug.org/.


2020 Update

It's been many years since I last answered this questions so I thought this deserves an update on the APM landscape.

  • AppDynamics has been bought by Cisco and free forever account they used to offer has been taken out from their website.
  • NewRelic has dropped their pricing from $149/month/host to $25/month/host to compete with the new comer to the APM market, Datadog which offers $31/month/host.
  • Datadog APM features are still light and leaves much to be desired for. However, I see them enhancing and improving these throughout the next year.
  • Ruxit has been bought by Dynatrace. No shocker here as Ruxit is built by ex Dynatrace Employees. This allowed Dynatrace to transform to a truly SaaS model for better. Say goodbye to that bulky Java client if you'd like to.
  • There are free/open-source options now as well. Checkout Apache Skywalking which is very popular in China among their top tech companies and PinPoint which offers a demo that you can try before installing. Both of these require you manage hosting so get ready to spin up few Virtual Machine and spend some time with installation and configuration.
  • I haven't tried either of these opensource APM solution so I'm in no position to recommend them, however, I've personally managed deploying all of these APM solutions for multiple organizations either on-premise or on cloud for hundreds of application/microservices. So I can say with confidence, you can't go wrong with any of the vendors if they fit your bill.


Originally Answered on October 2015

Here is a direct answer to your question

is there a software to measure that?

Yes, there is. I'm wondering why anyone hasn't mentioned it yet. Although the answers suggested above seems fine for a quick check but isn't scalable in the long run or for a bigger project.

Why not use an Application Performance Monitoring (APM) tool which are build exactly for that and so much more. Check out NewRelic, AppDynamics, Ruxit (all have free version) to monitor the execution time, resource usage, throughput of every application to the method level.


You have (at least) two solutions :

The quite "naïve" one is using microtime(true) tobefore and after a portion of code, to get how much time has passed during its execution ; other answers said that and gave examples already, so I won"t say much more.

This is a nice solution if you want to benchmark a couple of instructions ; like compare two types of functions, for instance -- it's better if done thousands of times, to make sure any "perturbating element" is averaged.

Something like this, so, if you want to know how long it take to serialize an array :

$before = microtime(true);

for ($i=0 ; $i<100000 ; $i++) {
    serialize($list);
}

$after = microtime(true);
echo ($after-$before)/$i . " sec/serialize\n";

Not perfect, but useful, and it doesn't take much time to set up.



The other solution, that works quite nice if you want to identify which function takes lots of time in an entire script, is to use :

  • The Xdebug extension, to generate profiling data for the script
  • Software that read the profiling data, and presents you something readable. I know three of those :
    • Webgrind ; web interface ; should work on any Apache+PHP server
    • WinCacheGrind ; only on windows
    • KCacheGrind ; probably only Linux and linux-like ; That's the one I prefer, btw

To get profiling files, you have to install and configure Xdebug ; take a look at the Profiling PHP Scripts page of the documentation.

What I generally do is not enable the profiler by default (it generates quite big files, and slows things down), but use the possibility to send a parameter called XDEBUG_PROFILE as GET data, to activate profiling just for the page I need.
The profiling-related part of my php.ini looks like this :

xdebug.profiler_enable = 0              ; Profiling not activated by default
xdebug.profiler_enable_trigger = 1      ; Profiling activated when requested by the GET parameter
xdebug.profiler_output_dir = /tmp/ouput_directory
xdebug.profiler_output_name = files_names

(Read the documentation for more informations)

This screenshot is from a C++ program in KcacheGrind : http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif
(source: sourceforge.net)

You'll get exactly the same kind of thing with PHP scripts ;-)
(With KCacheGrind, I mean ; WinCacheGrind is not as good as KCacheGrind...)

This allows you to get a nice view of what takes time in your application -- and it sometimes definitly helps to locate the function that is slowing everything down ^^

Note that Xdebug counts the CPU time spent by PHP ; when PHP is waiting for an answer from a Database (for instance), it is not working ; only waiting. So Xdebug will think the DB request doesn't take much time !
This should be profiled on the SQL server, not PHP, so...


Hope this is helpful :-)
Have fun !