Accurate way to measure execution times of php scripts

Php

Php Problem Overview


I want to know how many milliseconds a PHP for-loop takes to execute.

I know the structure of a generic algorithm, but no idea how to implement it in PHP:

Begin
init1 = timer(); // where timer() is the amount of milliseconds from midnight
the loop begin
some code
the loop end
total = timer() - init1;
End

Php Solutions


Solution 1 - Php

You can use the microtime function for this. From the documentation:

> microtime — Return current Unix timestamp with microseconds > > --- > > If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {
    
}
$time_elapsed_secs = microtime(true) - $start;

Solution 2 - Php

You can use microtime(true) with following manners:

Put this at the start of your php file:

//place this before any script you want to calculate time
$time_start = microtime(true);

// your script code goes here

// do something

Put this at the end of your php file:

// Display Script End time
$time_end = microtime(true);

//dividing with 60 will give the execution time in minutes other wise seconds
$execution_time = ($time_end - $time_start)/60;

//execution time of the script
echo '<b>Total Execution Time:</b> '.$execution_time.' Mins';

It will output you result in minutes.

Solution 3 - Php

You can use REQUEST_TIME from the $_SERVER superglobal array. From the documentation:

> REQUEST_TIME
> The timestamp of the start of the request. (Available since PHP 5.1.0.) > > REQUEST_TIME_FLOAT
> The timestamp of the start of the request, with microsecond precision. (Available since PHP 5.4.0.)

This way you don't need to save a timestamp at the beginning of your script. You can simply do:

<?php
// Do stuff
usleep(mt_rand(100, 10000));

// At the end of your script
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo "Did stuff in $time seconds\n";
?>

Here, $time would contain the time elapsed since the start of the script in seconds, with microseconds precision (eg. 1.341 for 1 second and 341 microseconds)


More info:

PHP documentation: $_SERVER variables and microtime function

Solution 4 - Php

Create file loadtime.php

<?php
class loadTime{
	private $time_start 	= 	0;
	private $time_end 		= 	0;
	private $time			=	0;
	public function __construct(){
		$this->time_start= microtime(true);
	}
	public function __destruct(){
		$this->time_end = microtime(true);
		$this->time = $this->time_end - $this->time_start;
		echo "Loaded in $this->time seconds\n";
	}
}

Than in the beggining of your script, after <?php write include 'loadtime.php'; $loadtime=new loadTime();

When page is loaded at the end there will be written "Loaded in x seconds"

Solution 5 - Php

$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
    // do something
}
$total = microtime(true) - $start;
echo $total;

Solution 6 - Php

Here is a function that times execution of any piece of PHP code, much like Python's timeit module does: https://gist.github.com/flaviovs/35aab0e85852e548a60a

How to use it:

include('timeit.php');
const SOME_CODE = '
        strlen("foo bar");
';
$t = timeit(SOME_CODE);
print "$t[0] loops; $t[2] per loop\n";

Result:

$ php x.php 
100000 loops; 18.08us per loop

Disclaimer: I am the author of this Gist

EDIT: timeit is now a separate, self-contained project at https://github.com/flaviovs/timeit

Solution 7 - Php

See [microtime()][1].

[1]: http://php.net/microtime "microtime()"

Solution 8 - Php

The way I do it is by using hrtime, it's created for performance metrics and it is independent from system time. hrtime does not get affected by system time changes. hrtime is available since PHP 7.3.0

$start = hrtime(true);
sleep(5); // do something, in your case a loop
$end = hrtime(true);
$eta = $end - $start;
// convert nanoseconds to milliseconds
$eta /= 1e+6;
echo "Code block was running for $eta milliseconds";

Output:

Code block was running for 5000.495206 milliseconds

Solution 9 - Php

You have the right idea, except a more precise timing is available with the microtime() function.

If what is inside the loop is fast, it is possible that the apparent elapsed time will be zero. If so, wrap another loop around the code and call it repeatedly. Be sure to divide the difference by the number of iterations to get a per-once time. I have profiled code which required 10,000,000 iterations to get consistent, reliable timing results.

Solution 10 - Php

Here is very simple and short method

<?php
$time_start = microtime(true);
//the loop begin
//some code
//the loop end
$time_end = microtime(true);
$total_time = $time_end - $time_start;
echo $total_time; // or whatever u want to do with the time
?>

Solution 11 - Php

I thought I'd share the function I put together. Hopefully it can save you time.

It was originally used to track timing of a text-based script, so the output is in text form. But you can easily modify it to HTML if you prefer.

It will do all the calculations for you for how much time has been spent since the start of the script and in each step. It formats all the output with 3 decimals of precision. (Down to milliseconds.)

Once you copy it to the top of your script, all you do is put the recordTime function calls after each piece you want to time.

Copy this to the top of your script file:

$tRecordStart = microtime(true);
header("Content-Type: text/plain");
recordTime("Start");

function recordTime ($sName) {
  global $tRecordStart;
  static $tStartQ;
  $tS = microtime(true);
  $tElapsedSecs = $tS - $tRecordStart;
  $tElapsedSecsQ = $tS - $tStartQ;
  $sElapsedSecs = str_pad(number_format($tElapsedSecs, 3), 10, " ", STR_PAD_LEFT);
  $sElapsedSecsQ = number_format($tElapsedSecsQ, 3);
  echo "//".$sElapsedSecs." - ".$sName;
  if (!empty($tStartQ)) echo " In ".$sElapsedSecsQ."s";
  echo "\n";
  $tStartQ = $tS;
}

To track the time that passes, just do:

recordTime("What We Just Did")

For example:

recordTime("Something Else")
//Do really long operation.
recordTime("Really Long Operation")
//Do a short operation.
recordTime("A Short Operation")
//In a while loop.
for ($i = 0; $i < 300; $i ++) {
  recordTime("Loop Cycle ".$i)
}

Gives output like this:

//     0.000 - Start
//     0.001 - Something Else In 0.001s
//    10.779 - Really Long Operation In 10.778s
//    11.986 - A Short Operation In 1.207s
//    11.987 - Loop Cycle 0 In 0.001s
//    11.987 - Loop Cycle 1 In 0.000s
...
//    12.007 - Loop Cycle 299 In 0.000s

Hope this helps someone!

Solution 12 - Php

Here's an implementation that returns fractional seconds (i.e. 1.321 seconds)

/**
 * MICROSECOND STOPWATCH FOR PHP
 *
 * Class FnxStopwatch
 */
class FnxStopwatch
{
	/** @var float */
	private $start,
			$stop;

	public function start()
	{
		$this->start = self::microtime_float();
	}
	public function stop()
	{
		$this->stop = self::microtime_float();
	}
	public function getIntervalSeconds() : float
	{
		// NOT STARTED
		if (empty($this->start))
			return 0;
		// NOT STOPPED
		if (empty($this->stop))
			return ($this->stop - self::microtime_float());

		return $interval = $this->stop - $this->start;
	}

	/**
	 * FOR MORE INFO SEE http://us.php.net/microtime
	 *
	 * @return float
	 */
	private static function microtime_float() : float
	{
		list($usec, $sec) = explode(" ", microtime());

		return ((float)$usec + (float)$sec);
	}
}

Solution 13 - Php

if you like to display that time in seconds:

<?php

class debugTimer
{
    private $startTime;
    private $callsCounter;

    function __construct()
    {
        $this->startTime = microtime(true);
        $this->callsCounter = 0;
    }

    public function getTimer(): float
    {
        $timeEnd = microtime(true);
        $time = $timeEnd - $this->startTime;
        $this->callsCounter++;
        return $time;
    }

    public function getCallsNumber(): int
    {
        return $this->callsCounter;
    }
}

$timer = new debugTimer();
usleep(100);
echo '<br />\n
    ' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();

usleep(100);
echo '<br />\n
    ' . $timer->getTimer() . ' seconds before call #' . $timer->getCallsNumber();

Solution 14 - Php

Here is my script to measure average time

<?php

$times = [];
$nbrOfLoops = 4;
for ($i = 0; $i < $nbrOfLoops; ++$i) {
    $start = microtime(true);
    sleep(1);
    $times[] = microtime(true) - $start;
}

echo 'Average: ' . (array_sum($times) / count($times)) . 'seconds';

Solution 15 - Php

You can find the execution time in second with a single function.

// ampersand is important thing here
function microSec( & $ms ) {
	if (\floatval( $ms ) == 0) {
		$ms = microtime( true );
	}
	else {
		$originalMs = $ms;
		$ms = 0;
		return microtime( true ) - $originalMs;
	}
}

// you don't have to define $ms variable. just function needs
// it to calculate the difference.
microSec($ms);
sleep(10);
echo microSec($ms) . " seconds"; // 10 seconds

for( $i = 0; $i < 10; $i++) {
	// you can use same variable everytime without assign a value
	microSec($ms);
	sleep(1);
	echo microSec($ms) . " seconds"; // 1 second
}

for( $i = 0; $i < 10; $i++) {
	// also you can use temp or useless variables
	microSec($xyzabc);
	sleep(1);
	echo microSec($xyzabc) . " seconds"; // 1 second
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDomingoSLView Question on Stackoverflow
Solution 1 - PhpTim CooperView Answer on Stackoverflow
Solution 2 - PhpAditya P BhattView Answer on Stackoverflow
Solution 3 - PhpIwazaruView Answer on Stackoverflow
Solution 4 - PhpSolo OmsarashviliView Answer on Stackoverflow
Solution 5 - PhpDvirView Answer on Stackoverflow
Solution 6 - PhpflaviovsView Answer on Stackoverflow
Solution 7 - PhppatapizzaView Answer on Stackoverflow
Solution 8 - PhpWaqlehView Answer on Stackoverflow
Solution 9 - PhpwallykView Answer on Stackoverflow
Solution 10 - PhpDeepak KumarView Answer on Stackoverflow
Solution 11 - PhpazoundriaView Answer on Stackoverflow
Solution 12 - PhpmilsView Answer on Stackoverflow
Solution 13 - PhpEugene KaurovView Answer on Stackoverflow
Solution 14 - PhpWilliam DesportesView Answer on Stackoverflow
Solution 15 - PhpkodmanyaghaView Answer on Stackoverflow