Get run time php

How to Measure Script Execution Time in PHP

The time that is required for executing a PHP script, is known as script execution time.

It is recommended to use a clock for calculating it. If you know the time before the script execution and after it, you will manage to get the execution time easily.

Let’s take a look at a script sample:

 for ($i = 1; $i 1000; $i++) < echo "Hello W3docs!"; > ?>

Getting the Clock Time with microtime()

The microtime() function is used for getting the clock time. First, it should be used before the script starts, then, at the end of it. Afterwards, the formula (End_time – Start_time) should be used.

With the help of the microtime() function, time is returned in seconds. The execution time is not fixed, it is decided by the processor.

To be more precise, let’s see an example:

 // Starting clock time in seconds $start_time = microtime(true); $a = 1; // Start loop for ($i = 1; $i 10000000; $i++) < $a++; > // End clock time in seconds $end_time = microtime(true); // Calculating the script execution time $execution_time = $end_time - $start_time; echo " Execution time of script = " . $execution_time . " sec"; ?>
Execution time of script = 1.4305651187897 sec

Describing the microtime() Function

The microtime() function of PHP is used for returning the current Unix timestamp. It returns a string in microseconds.

Читайте также:  Your Title Here

Passing a boolean value as a parameter of this method will return the current time in seconds.

Источник

Accurate way to measure execution times of php scripts

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 

You can fiddle around with swaths of microtime() statements if you need this in production, but if it’s just for testing, just use xdebug’s profiler for instance. No messy code is a real plus.

17 Answers 17

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.

$start = microtime(true); while (. ) < >$time_elapsed_secs = microtime(true) - $start; 

I know this is waaaaaay too late (almost 4 years), but as a comment. using these calculations (with the parameter get_as_float as true ) will give you results in seconds, according to PHP documentation.

@patrick and that’s what I said: if get_as_float is true , microtime() returns the value representing the seconds.

While this is a very old post, we should refer to the fact that the float returned does contain the microseconds. Best solution is to times this by 1000. see stackoverflow.com/questions/3656713/… as an example..

«For performance measurements, using hrtime() is recommended.» php.net/manual/en/function.hrtime.php (PHP 7 >= 7.3.0, PHP 8)

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

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, otherwise seconds $execution_time = ($time_end - $time_start)/60; //execution time of the script echo 'Total Execution Time: '.$execution_time.' Mins'; 

It will output you result in minutes .

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:

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:

According to the linked documentation, $time will contain the difference in seconds, not in microseconds.

@WimDeblauwe To clarify, yes the result is in seconds. But with microsecond precision. e.g. 1.1 equates to 1 second + 100 microseconds.

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"; > > 

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

Neat! But if you don’t explicitly destroy your object, the output would appear after the closing tag which is invalid

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

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"; 

Code block was running for 5000.495206 milliseconds

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

include('timeit.php'); const SOME_CODE = ' strlen("foo bar"); '; $t = timeit(SOME_CODE); print "$t[0] loops; $t[2] per loop\n"; 
$ 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

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.

Here is very simple and short method

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") 
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
// 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 

Источник

Determine how long PHP executed so far

I need to determine how long a PHP function has been running so far. What are some options to find out how long some PHP code takes to run? I’m using zend framework.

4 Answers 4

Call microtime(true) function to fetch current time with milisecond resolution.

thanks for the reply, but implementing that within a framework is not straightforward. besides, it’s not accurate because the processing time used by the framework itself is not counted

I would expect you would need a real elapsed time, not an elapsed time — ‘framework time’. As far as implementing it into existing code goes, the easiest (not necessarily the best) way could be using a singleton, to have the timer globally accessible.

@Nate You’re quite right about that. + , — and . have the same operator precedence, and are left associative. This means first concatenation would be performed before subtraction.

microtime — Return current Unix timestamp with microseconds

You could simply use PHP’s standard timeout, and implement a shutdown function.

function say_goodbye() < if (connection_status() == CONNECTION_TIMEOUT) < . do your special processing to save the process state here . then formulate a response for the browser >> // function say_goodbye() register_shutdown_function("say_goodbye"); 

Note that you can set the shutdown function to accept parameters

function say_goodbye($controller1,$controller2) < if (connection_status() == CONNECTION_TIMEOUT) < . do your special processing to save the process state here . then formulate a response for the browser >> // function say_goodbye() $ctl1 = new DBController(); $ctl2 = new OPController(); register_shutdown_function("say_goodbye",$ctl1,$ctl2); 

Источник

Оцените статью