Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How to check speed in PHP?

Use timestamp function to measure the speed of code. The timestamp function placed twice in a program one at starting of program and another at end of the program. Then the time difference between end time and start time is the actual speed of code.

How do I see running time in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.

How does PHP calculate time of execution?

Use PHP's microtime() function to measure script execution time. Make more performant decisions with your application.

Is PHP a performance?

PHP may not be as fast as compiled server side languages, but it is still pretty fast and does the job. The "speed" aspect of php has more to do with the user experience than with the performance itself.


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 !


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/.


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 

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.


If you want to quick test performance of a framework, you can put in index.php file

//at beginning
$milliseconds = round(microtime(true) * 1000);

//and at the end
echo round(microtime(true) * 1000) - $milliseconds;

Every time you will get execution time in milliseconds. Because microseconds is not too useful in testing a framework case.


I've been using XHProf lately http://pecl.php.net/package/xhprof. It was originally developed by Facebook and it comes with a decent web interface.


I'd like to share with you a self made function I use to measure the speed of any existing function up to 10 arguments:

function fdump($f_name='', $f_args=array()){

    $f_dump=array();
    $f_result='';

    $f_success=false;

    $f_start=microtime();
    $f_start=explode(' ', $f_start);
    $f_start=$f_start[1] + $f_start[0];

    if(function_exists($f_name)){

        if(isset($f_args[0])&&is_array($f_args[0])){
            if($f_result=$f_name($f_args)){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[1])){
            if($f_result=$f_name($f_args[0])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[2])){
            if($f_result=$f_name($f_args[0],$f_args[1])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[3])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[4])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[5])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[6])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[7])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[8])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[9])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7],$f_args[8])){
                $f_success=true;
            }
        }
        elseif(!isset($f_args[10])){
            if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7],$f_args[8],$f_args[9])){
                $f_success=true;
            }
        }
    }
    $f_end=microtime();
    $f_end=explode(' ', $f_end);
    $f_end=$f_end[1] + $f_end[0];

    $f_time=round(($f_end - $f_start), 4);
    $f_dump['f_success']=$f_success;
    $f_dump['f_time']=$f_time;
    $f_dump['f_result']=$f_result;

    var_dump($f_dump);exit;

    //return $f_result;

}

Example

function do_stuff($arg1='', $arg2=''){
    return $arg1.' '.$arg2;
}

fdump('do_stuff',array('hello', 'world'));

Returns

  array(3) {
    ["f_success"]=>
    bool(true)
    ["f_time"]=>
    float(0)            //too fast...
    ["f_result"]=>
    string(11) "hello world"
  }