Tracking the script execution time in PHP Tracking the script execution time in PHP php php

Tracking the script execution time in PHP


If all you need is the wall-clock time, rather than the CPU execution time, then it is simple to calculate:

//place this before any script you want to calculate time$time_start = microtime(true); //sample scriptfor($i=0; $i<1000; $i++){ //do anything}$time_end = microtime(true);//dividing with 60 will give the execution time in minutes otherwise seconds$execution_time = ($time_end - $time_start)/60;//execution time of the scriptecho '<b>Total Execution Time:</b> '.$execution_time.' Mins';// if you get weird results, use number_format((float) $execution_time, 10) 

Note that this will include time that PHP is sat waiting for external resources such as disks or databases, which is not used for max_execution_time.


On unixoid systems (and in php 7+ on Windows as well), you can use getrusage, like:

// Script start$rustart = getrusage();// Code ...// Script endfunction rutime($ru, $rus, $index) {    return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));}$ru = getrusage();echo "This process used " . rutime($ru, $rustart, "utime") .    " ms for its computations\n";echo "It spent " . rutime($ru, $rustart, "stime") .    " ms in system calls\n";

Note that you don't need to calculate a difference if you are spawning a php instance for every test.


Shorter version of talal7860's answer

<?php// At start of script$time_start = microtime(true); // Anywhere else in the scriptecho 'Total execution time in seconds: ' . (microtime(true) - $time_start);

As pointed out, this is 'wallclock time' not 'cpu time'