How to find out the time spent inside a PHP script? - php

I'm executing a PHP script that takes about a minute to finish and although the default time limit is set to 30 seconds, the script continues its execution after that limit.
I found out, that the limit only affects the time that is spent inside the script itself and not the time spent in library functions like database queries etc.
Is there a way to find out the time that is actually spent inside the script? I tried to use getrusage, but it doesn't seem to return the appropriate values for this problem.
Example:
<?php
$time = microtime(TRUE);
sleep(100);
echo 'Time: ', microtime(TRUE) - $time;
?>
The script waits for 100 seconds and does not terminate after the time limit of 30 seconds.
According to the documentation of set_time_limit, the time that is spent inside the sleep function (100 seconds) is not involved in the calculation of the execution time, because it's an external (library) function.

I just want to know how much of the execution time is spent inside my script and how much is spent in library functions.
Use XDebug Profiler for it.

I'm guessing you want something like this:
<?php
// the whole operation
$time1 = time();
// perform some functions
$s = file_get_contents("somefilename");
$time2 = time();
// perform some library functions
$rs = some_third_party_library_function();
$time3 = time();
// Show results
echo "Overall Time spent: " . ($time3 - $time1) . "s <br>";
echo "Time spent reading file: ". ($time2 - $time1) . "s <br>";
echo "Time spent by Third Party Library: " . ($time3 - $time2) . "s <br>";
?>

You can mark the start time before entering the script, then mark the end time after the script ends. Echo the difference then.
<?php
$a=time();
sleep(5);
$b=time();
echo $b-$a;
?>

If you need to measure the execution time of individual functions vs standard or built-in PHP functions, this is best done with a proper debugger and code profiler. Xdebug does exactly that.

Don't know how complicated your script is, however you can just add a comment to all your library functions calls. If your code requires their returned values in order to be properly executed, replace them with constant values (that could have been returned by these functions). For example:
$result = mysql_query( ... )
replace with:
// $result = mysql_query( ... )
$result = // resource, boolean or whatever you want
Then run the script and calculate the execution time using Coding-Freak's suggestion.
If you prefer Rio Bautista's approach you may find some functions that calculates section's time.

Related

How can I resolve a time() vs microtime() problem?

I am trying to start several processes as close to the same time as possible. A cronjob selects all items to be processed from the database a minute prior to the actual time these processes need to start, and then starts a child process for each record found.
As it can take several seconds to run through the database and spawn the child processes, I am trying to create a sleep or usleep delay so that each spawned child process starts as close as possible to the top of the next minute.
In testing, I have noticed some differences between the child start times returned by time() and microtime().
Here's the code I have to create the delay:
$unixtime_now = time();
$unixMicrotime_now = microtime(true);
$timeToStart = $unixtime_now + 2;
$timeToSleep = $timeToStart - $unixMicrotime_now;
$timeToSleep = number_format($timeToSleep,6);
$timeToSleep = str_replace('.','',$timeToSleep);
usleep ($timeToSleep);
$startedAtMicrotimeFloat = microtime(true);
$startedAtTime = time();
$date1 = date("H:i:s", $startedAtMicrotimeFloat);
$date2 = date("H:i:s", $startedAtTime);
echo "Unixtime Now = $unixtime_now<br />UnixMicroTime Now = $unixMicrotime_now<br />Time to Start = $timeToStart<br />Time to Sleep = $timeToSleep<br />Started at Time = $startedAtTime - $date2<br />Started at MicroTimeFloat = $startedAtMicrotimeFloat - $date1";
Note that I used 2 seconds rather than 60 seconds for the offset to facilitate speed in testing.
2 questions:
1) No matter how many times I run this, the times returned by time() are ALWAYS 1 second before the times returned by microtime(). For example:
Started at Time = 1555765444 - 09:04:04
Started at MicroTimeFloat = 1555765445.0002 - 09:04:05
This is probably a forest for the trees issue, but does anyone have an idea why this is or how I can resolve it?
2) Are there any drawbacks to having a usleep() delay that can be as long as 59 seconds? Would it be better to use sleep() and accept the the child processes might start at 1555765445.9999 - 09:04:05 rather than 1555765445.0002 - 09:04:05, or up to almost a full second later?
Thanks in advance.
Alan
Per Dave's suggestion, I edited the code as follows:
$date1 = date("H:i:s", microtime(true));
$date2 = date("H:i:s", time());
I still get the same result:
Started at Time = 1555876342 - 15:52:22
Started at MicroTimeFloat = 1555876343.0003 - 15:52:23
The microtime() result, which I suspect to be accurate, is later than the time() result by 1.0003 seconds.

php set_time_limit less than one second

The question is simple, I would like to check a database to serve customised content to a site visitor, but failover and serve a generic page if this function takes more then 800ms to execute. (Target time for the server response is 1000ms).
I've seen the set_time_limit function, however this takes an integer in seconds as the argument.
My question: is there something similar that can be used with values of less than 1 second?
I'm looking for something like:
void set_time_limit_ms ( int $milliseconds )
set_time_limit_ms (800)
doesn't exist. you just could emulate it with a tick function:
declare(ticks=1); // or more if 1 takes too much time
$start = microtime(1);
register_tick_function(function () use ($start) {
(microtime(1) - $start < 0.8) or die();
});
You will not be able to use this function to prevent a query that is running longer than you expected. This only measures the actual script execution time. Here is an bit from the manual.
The set_time_limit() function and the configuration directive
max_execution_time only affect the execution time of the script
itself. Any time spent on activity that happens outside the execution
of the script such as system calls using system(), stream operations,
database queries, etc. is not included when determining the maximum
time that the script has been running. This is not true on Windows
where the measured time is real.
Yes there is, I often use microtime. see
http://php.net/manual/en/function.microtime.php
<?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";
?>

The time that it takes for a function to run

What is the best way for getting how long a function takes to run until finish and then storing that number in a variable in PHP ?
How I would think about doing this is get the time right before the function is executed and right after and then take the difference of the former from the latter, but I don't know how get the time in php.
Also, I am trying to get the units to be in tenths and hundredths of second (.42 seconds), hopefully the function takes less than a second to complete so if anyone can help me convert it to those units, i'd appreciate that.
You can do that using microtime().
$start = microtime(true);
for ($x=0;$x<10000;$x++) {}
$end = microtime(true);
echo 'It took ' . ($end-$start) . ' seconds!';
See "Example #1 Timing script execution with microtime()" in the documentation.
http://docs.php.net/manual/en/function.microtime.php
$time = time();
call_your_function();
$time = time()-$time;
echo "The function took $time seconds to run\n";

how to display php search engine execution time and number of results before the results

ok so i built a php search engine and it was working beautifully, but some people said to me that it was slow.
maybe it may appear slow on their machines when the thing outputs the results table on html but i know it's running ludicrously fast.
so i decided to make a fancy feature like the one many search engines like google have saying that ''your search returned X results in Y time'' as a way of telling people that probably isn't my search engine fault that they're taking a long time to see the results for their query.
i've made the feature that pretty much confirms what i already know, that is that the search engine is fast.
the problem is the results are echoed before the timer/resultcounter thing is, because for it to count the results it already has to have the results and for it to display the time it took to find them obviously the search engine had to finish running.
i'm using html+css+php for this project and i don't want to have to use javascript, how should i display the timer / results counter before the actual results?
You can run the search queries with the time code, then echo them after the search has finished with the time code coming first.
$start = microtime(true);
$searchdata = //Search Functions
$end = microtime(true);
$time = ($end - $start);
echo $time."".$searchdata
<?PHP
$print=null;
$start=microtime();
echo 'etc etc you just found the results<br><br>';
$print= '<br><br>It took '. number_format(microtime()-$start,12).' seconds to find the results.<br><br>';
echo 'etc etc do what else is to be done, end of script<br>';
echo '__________________________________________________________<br><br>';
echo $print,'It took ', number_format(microtime()-$start,12),' seconds in total.';
?>
$start_time = microtime(true);
.
.
//Search Logic
.
.
$end_time = microtime(true);
$time = ($end_time - $start_time);
echo "Search Time : ".$time." sec\t";

PHP get exact time a particular line is executed

I'm trying to perform a simple benchmark on a script I have. First I tried to just add something like:
echo 'After Checklist: '. date('h:i:s:u A') ."<br />";
but it just prints out the same time for a lot of the times - it isn't until a includes script is ran that it returns a different time. Is there anyway to do this? Or something similar - I basically just want to see where the bottleneck is so I can increase performance.
You want to use the microtime function which will return the current Unix timestamp with microseconds.
From here you can do simple subtraction from the start and end time to get the desired results. The trick however, is to pass in "true" into the function so it returns a float value, rather than a string.
An example, as posted on php.net is this:
<?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";
?>
I think you need microtime:
http://php.net/manual/en/function.microtime.php

Categories