What is the best way to see how long it takes for your PHP script to run?
I was thinking something like this:
$start_time = time(); //this at the beginning
$end_time = time(); //this at the end
echo = $end_time-$start_time;
But how can I make it into something that is readable to me and make sense to me?
If you want any further granularity to your timing than seconds, you'll need to use microtime() (Return current Unix timestamp with microseconds)
<?php
$time_start = microtime(true);
// Sleep for a while
usleep(100);
$time_end = microtime(true);
$time = $time_end - $time_start;
echo "Did nothing in $time seconds\n";
?>
** Below was added later **
As far as formatting this result further:
Well, depending on what you're doing, you typically don't have scripts going past a minute. You definitely shouldn't have anything exceeding an hour. (If you do, you need to ask yourself what you are doing with your life)
With that in mind, all you need is simple calculations:
$tmp = floor($time);
$minutes = $tmp / 60;
$seconds = ($tmp % 60) + ($time - $tmp);
$output = 'Script took ';
if ($minutes > 0) $output .= $minutes . ' minutes and ';
$output .= $seconds . ' seconds to complete.';
echo $output;
(This isn't tested, and it could potentially be optimized, but should start you in the right direction)
I would use microtime(TRUE) instead. That'll give you better results with microsecond resolution. There's also the PECL APD extension which profiles scripts.
Expanding a bit on APD, assuming one has APD installed, you just need to add the line
apd_set_pprof_trace();
to the top (or whenever you want to start tracing) of your script. It generates a profiling file with pprofp which generates very readable output
Real User System secs/ cumm
%Time (excl/cumm) (excl/cumm) (excl/cumm) Calls call s/call Memory Usage Name
--------------------------------------------------------------------------------------
100.0 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0000 0.0009 0 main
56.9 0.00 0.00 0.00 0.00 0.00 0.00 1 0.0005 0.0005 0 apd_set_pprof_trace
28.0 0.00 0.00 0.00 0.00 0.00 0.00 10 0.0000 0.0000 0 preg_replace
The example output is from the PHP manual.
I personally find APD extremely useful and use it quite frequently in heavily-hit scripts.
Knowing how long something takes to run is one thing, finding out where (in your php operations) it slows down and why is another question.
If you're serious about find an answer to the latter question then install xdebug, and you get the bonus of not having to call the likes of microtime() which itself slows down your script.
http://xdebug.org/docs/profiler
http://xdebug.org/docs/
Is this a web-accessible script (i.e. http://www.yoursite.com/BLA.php), or a script that you're running through the command line? If it's a command line script, you can use the time command:
time php FILE.php
Otherwise, microtime is probably your best bet.
I find this class to be useful to time the scripts, microtime turn out to be friend in that:
class timer
{
private $start_time = NULL;
private $end_time = NULL;
private function getmicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function start()
{
$this->start_time = $this->getmicrotime();
}
function stop()
{
$this->end_time = $this->getmicrotime();
}
function result()
{
if (is_null($this->start_time))
{
exit('Timer: start method not called !');
return false;
}
else if (is_null($this->end_time))
{
exit('Timer: stop method not called !');
return false;
}
return round(($this->end_time - $this->start_time), 4);
}
# an alias of result function
function time()
{
$this->result();
}
}
Related
I want to calculate the execution time of popen function in PHP. The function is not provide execution time as default.
My pseudo code like below;
$handle = popen($cmd, 'r');
while (!feof($handle)) {
$buffer = fgets($handle, FREAD_BUFFER_SIZE);
$out .= $buffer . " ";
}
I found a solution in here but I am not sure it's the right way.
Consider using the time() or microtime(true) function.
$currentTimeinSeconds = microtime(true);
This stores the seconds passed from the instance it was declared to 1/01/1970. Make two variables (ex. T1 and T2) and simply subtract the second to the first to get the execution time.
$t1= microtime(true)
[function]
$t2= microtime(true)
ex_time=$t2-$t1
Like there is a simple script which shouldn’t take long, but when the CPU switched to another job mid-script and was doing that job for a while, does it affect the difference between the two calls of microtime() on each end of the small script?
microtime() returns a value representing the realtime. A possible usage is:
$duration = -microtime(true);
// .... do something .....
$duration += microtime(true);
If you want the CPU usage time, use function rusage()
$ru_start = getrusage();
// .... do something .....
$ru_end = getrusage();
$elapsed_user = $ru_end['ru_utime.tv_sec'] * 1000000
+ $ru_end['ru_utime.tv_usec']
- $ru_start['ru_utime.tv_sec'] * 1000000
- $ru_start['ru_utime.tv_usec'];
$elapsed_system = $ru_end['ru_stime.tv_sec'] * 1000000
+ $ru_end['ru_stime.tv_usec']
- $ru_start['ru_stime.tv_sec'] * 1000000
- $ru_start['ru_stime.tv_usec'];
Ok, I know this is not the first question about microtime and number_format but it seem there is no one able to come up with a dummy proof answer. So, as the dummy, here is my question:
How can I output my result from 2 microtime(true) variables in millisecondes. By that I mean 1 being 1 milliseconds and 1000 being 1 secondes.
So if it took less then a millisecondes, i get 1. If it took 1/2 of a second, I get 500.
I currently do this:
number_format((microtime(true)-$timetrace), 4)
And I get this:
1,391,490,671.8339
=)
$timetrace was set before in the code as $timetrace = microtime(true). Thansk for the help and if this was answer before in a one line command, I am truly sorry for asking that again.
This has nothing to do with number_format.
My bet is, you did not put what you intended in your $timetrace variable.
See this example:
<?php
$timetrace = microtime(true);
sleep (1); // wait about 1 second
$elapsed_time = microtime(true) - $timetrace;
echo "$elapsed_time<br>";
echo number_format($elapsed_time, 4) . "<br>";
?>
output:
1.0120580196381
1.0121
Based on kuroi neko suggestion, I did built a little funciton and it work perfectly! Thank you a lot!!
Function ms($overall=0)
{
global $timetrace;
global $starttrace;
if ($overall==1){
$result = microtime(true) - $initialtrace;
}else{
$result = microtime(true) - $timetrace;
}
$result = number_format($result, 4);
$result = $result * 1000;
if ($result < 1)$result = 1;
// Reset timetrace
$timetrace = microtime(true);
return $result." ms<br>";
}
In the code I just have to put:
if (isset($timetrace)) echo "CPU$==# initiation time = ".ms();
That give me the time spent between my last echo. (isset is actually a variable I configure at the beginning to see if I am in 'time debugging mode')
If I pass 1 - echo "CPU$==# initiation time = ".ms(1); - I get the result of the total duration of the script since the top of the page instead of the last echo.
Here is a sample of the output:
CPU$==# INSERT = 12.4 ms
CPU$==# DATE SET FOR GOOGLE QUERY = 530.4 ms
CPU$==# GOOGLE QUERY EXECUTED = 308.8 ms
CPU$==# INSERT 606 ROW = 12290.3 ms
CPU$==# CLOSE LOG WITH SUCCESS = 25.4 ms
Success
And yeah, performance is really terrible. The first 530 ms just to prepare the google query is way too high and 12 seconds to insert 600 rows is insane. Something is badly broken somewhere! =) But at least, now I will be able to benchmark my progression.
Thank you!!!
please tell me how to make a delay function to delay functions!
DelayCommand(functionToDelay, Delaytime);
..? in php 5.3+
thanks for any help
function delayCommand($callback, $delayTime) {
sleep($delayTime);
$callback();
}
This should work, consider switching out sleep() to usleep().
function DelayCommand($functionToDelay, $delayTimeInSeconds) {
sleep($delayTimeInSeconds);
$functionToDelay();
}
DelayCommand(function() { echo "yes"; }, 5);
(Code is untested)
function delayCommay($function, $nano){
usleep($nano);
$function();
}
Will do the trick however it is synchronous. So if you make a call to delayCommand it will delay your whole script until it has run the command.
If you want it done asynchronously, see my answer here: Scheduling php scripts
For your information, here's a list of related functions:
sleep() / usleep() - Sleep for an amount of (micro)seconds.
time_sleep_until() - Sleep until a timestamp.
time_nanosleep() - Sleep for an amount of seconds and nanoseconds.
Here is what I have for delaying a function in MS, Sleep and Usleep pause the execution of the whole script, this seems to work pretty well
public function DelayTime($ms){
$now = microtime();
$finishtime = ($now + $ms);
while($now < $finishtime){
$now = time();
if($now >= $finishtime){ break; }
}
return true;
}
Is there a PHP equivalent to setting timeouts in JavaScript?
In JavaScript you can execute code after certain time has elapsed using the set time out function.
Would it be possible to do this in PHP?
PHP is single-threaded, and in general PHP is focused on the HTTP request cycle, so this would be tricky to allow a timeout to run code, potentially after the request is done.
I can suggest you look into Gearman as a solution to delegate work to other PHP processes.
You can use the sleep() function:
int sleep ( int $seconds )
// Delays the program execution for the given number of seconds.
Example:
public function sleep(){
sleep(1);
return 'slept for 1 second';
}
This is ugly, but basically works:
<?php
declare(ticks=1);
function setInterval($callback, $ms, $max = 0)
{
$last = microtime(true);
$seconds = $ms / 1000;
register_tick_function(function() use (&$last, $callback, $seconds, $max)
{
static $busy = false;
static $n = 0;
if ($busy) return;
$busy = true;
$now = microtime(true);
while ($now - $last > $seconds)
{
if ($max && $n == $max) break;
++$n;
$last += $seconds;
$callback();
}
$busy = false;
});
}
function setTimeout($callback, $ms)
{
setInterval($callback, $ms, 1);
}
// user code:
setInterval(function() {
echo microtime(true), "\n";
}, 100); // every 10th of a second
while (true) usleep(1);
The interval callback function will only be called after a tickable PHP statement. So if you try to call a function 10 times per second, but you call sleep(10), you'll get 100 executions of your tick function in a batch after the sleep has finished.
Note that there is an additional parameter to setInterval that limits the number of times it is called. setTimeout just calls setInterval with a limit of one.
It would be better if unregister_tick_function was called after it expired, but I'm not sure if that would even be possible unless there was a master tick function that monitored and unregistered them.
I didn't attempt to implement anything like that because this is not how PHP is designed to be used. It's likely that there's a much better way to do whatever it is you want to do.
Without knowing a use-case for your question it's hard to answer it:
If you want to send additional data to the client a bit later you can do a JS timeout on the client side with a handler that will make a new HTTP request to PHP.
If you want to schedule some task for a later time you can store that in a database and poll the DB in regular intervalls. It's not the best peforming solution but relatively easy to implement.
if ($currenturl != $urlto)
exit( wp_redirect( $urlto ) );
You can replace above two line with below code inside your function
if ($currenturl != $urlto)
header( "refresh:10;url=$urlto" );