Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Date and Time Functions : microtime

microtime

Return current Unix timestamp with microseconds (PHP 4, PHP 5)
mixed microtime ( [bool get_as_float] )

Example 456. Timing script execution with microtime()

<?php
/**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float()
{
   list(
$usec, $sec) = explode(" ", microtime());
   return ((float)
$usec + (float)$sec);
}

$time_start = microtime_float();

// Sleep for a while
usleep(100);

$time_end = microtime_float();
$time = $time_end - $time_start;

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

Example 457. Timing script execution in PHP 5

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

Related Examples ( Source code ) » microtime





Code Examples / Notes » microtime

rsalazar

Yet another way to achieve the same effect without the loss of decimals is with the PCRE replace function (preg_replace), which also seems to be a _bit_ faster (about 2.5E-05 sec):
<?php
   $float_time = preg_replace('/^0?(\S+) (\S+)$/X', '$2$1', microtime());
?>
PS unluckypixie, "james at gogo dot co dot nz" wrote the same at Dec/2004


chris

Want to generate a unique default password for a user?
$password = md5(microtime());
That is much better than using a random number!


blade106nospam

To simulate the new parameter under PHP 5 and below, just use :
time() + microtime()
this can be used as following :
<?php
$start = time() + microtime();
// do some stuff here
echo time() + microtime() - $start, ' seconds to produce result';
?>
Enjoy ;o)


debo jurgen
To generate parsing time of a HTML page:
This works with a STATIC var. So You do
not need to store starttime at all.
Usage : Call this twice on top of Your template,
       and before </body>
function stopwatch(){
  static $mt_previous = 0;
  list($usec, $sec) = explode(" ",microtime());
  $mt_current = (float)$usec + (float)$sec;
  if (!$mt_previous) {
     $mt_previous = $mt_current;
     return "";
  } else {
     $mt_diff = ($mt_current - $mt_previous);
     $mt_previous = $mt_current;
     return sprintf('%.16f',$mt_diff);
  }
}


admin

This little function comes in handy if you want a single integer when your server doesn't have php >= 5.0
It returns seconds passed unix epoch to the microsecond. Or microseconds since unix epoch.
<?php
//A hack for PHP < 5.0
function utime($inms){
$utime = preg_match("/^(.*?) (.*?)$/", microtime(), $match);
$utime = $match[2] + $match[1];
if($inms){
$utime *=  1000000;
}
return $utime;
}
//Example:
print utime();
//Returns:
//1156127104.746352 Seconds
//Example two:
print utime(1);
//Returns:
//1156127104746352 Microseconds
?>


a dot winkelbauer

this is the function i use instead of microtime() with php < 5. it returns the whole time (seconds and microseconds) as a string or as a float.
<?php
function myMicrotime($get_as_float = false)
{
   list($msec, $sec) = explode(" ", microtime());
   $time = $sec . substr($msec, 1);
   return $as_float === false ? $time : (float)$time;
}
?>


z0d

The shortest way for PHP4 users really is
$ts = strtok(microtime(), ' ') + strtok('');


zenofeller

The fact that kayode's example outputs a letter, then a number, then a letter then a number DOESN'T make it any more predictable than your example that outputs a letter, then a letter, then a letter.
They're both just as unpredictable, namely, algorithmically generated random numbers.


james

The docs above show a pretty verbose function for emulating the float functionality available in PHP 5.  Here's a one liner that does the same job without the overhead of the function call.
$floattime = (float) array_sum(explode(' ', microtime());


admin

The code provided by joelatlearnossdotcom is incorrect. That will only produce the microseconds of the current time. Here's what it should look like:
<?
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;
// --------------
// your code here
// --------------
$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 6);
?>
with $total_time being the script execution time.


fabian otto

The Code from the man underme has a error!
Here the right!
I needed a way to give the total time to execute a whole page of code that included MySQL code as well and the exmples show did not quite help, Althought they lead me to the answer.
<?PHP
$starttimer = time()+microtime();
/*
...Page of Code
...MySQL Code
*/
$stoptimer = time()+microtime();
$timer = round($stoptimer-$starttimer,4);
echo "Page created in $timer seconds.";
?>
Result:
Page created in 4.1368 seconds.


philip dot waters dot pryce

Surely This Would Be Easyer  Chris (21-Jan-2005 03:17)
Quote:
Want to generate a unique default password for a user?
$password = md5(microtime());
That is much better than using a random number!
-----
$password = md5(rand(0,microtime()));
That Would Most Definate Be Much More Random :D And Harder To Break


helenadeus

Sometimes it is useful to generate a sequential unique ID. This one uses microtime() to generate a unique string of numbers that varies every time and generates sequential numbers.
<?
function seqid()
{
list($usec, $sec) = explode(" ", microtime());
list($int, $dec) = explode(".", $usec);
return $sec.$dec;

}
?>


alien999999999

so true, use mysql auto_increment!
but for those, who wish to output logs with those totally stupid timestamps (like qmail) (instead of nicely readable normal timestrings), use this for the really shortest way:
function stupid_timestamp()
{
list($msec,$sec)=split(' ',microtime);
return $sec.'.'.$msec;
}


logix dot spam-me-not

Regarding discussion about generation of passwords using microtime.
Its proberbly "ok" for a first-time password, but it is NOT better than random.
Cryptographicly there will very limited keyspace to test of you use this method.
If the stored password hash was to fall into wrong hands it would quite easily be cracked, as there are several factors that limits the combinations. Especially if you know ca. what time the password was issued.
The string output from microtime looks like this:
- 0.93839800 1131978543
The first number is always 0.
On my computer, it seems that the 7th and 8th number are always "00", so lets assume that as well.
In the last number (the epoch timestamp), there are only 3.600 combinations (=seconds) in an hour.
That leaves 6 unpredictable digits (the 938398 above).
thats 10^6 = 1.000.000 (combinations).
1.000.000 combinations can be checked in 55 seconds on my 3.2ghz
So the time it takes to crack is 55 seconds, times the number of seconds youre guessing (in the timestamp)..
If, say, you know ca. when the password was created, +-5minutes. That a 10 minute total, a span of 600 combinations, that would be:
600(seconds) * 55 (seconds crack time) = 9 hours.
And that using just 1 computer..


edorfaus

Of the methods I've seen here, and thought up myself, to convert microtime() output into a numerical value, the microtime_float() one shown in the documentation proper(using explode,list,float,+) is the slowest in terms of runtime.
I implemented the various methods, ran each in a tight loop 1,000,000 times, and compared runtimes (and output). I did this 10 times to make sure there wasn't a problem of other things putting a load spike on the server. I'll admit I didn't take into account martijn at vanderlee dot com's comments on testing accuracy, but as I figured the looping code etc would be the same, and this was only meant as a relative comparison, it should not be necessary.
The above method took on average 5.7151877 seconds, while a method using substr and simply adding strings with . took on average 3.0144226 seconds. rsalazar at innox dot com dot mx's method using preg_replace used on average 4.1819633 seconds. This shows that there are indeed differences, but for normal use noone is going to notice it.
Note that the substr method mentioned isn't quite the one given anonymously below, but one I made based on it:
<?php
$time=microtime();
$timeval=substr($time,11).substr($time,1,9);
?>
Also worth noting is that the microtime_float() method gets faster, and no less accurate, if the (float) conversions are taken out and the variables are simply added together.
Any of the methods that used + or array_sum ended up rounding the result to 2 digits after the decimal point, while (most of) the ones using preg_replace or substr and . kept all the digits.
For accurate timing, since floating-point arithmetic would lose precision, I stored microtime results as-is and calculated time difference with this function:
<?php
function microtime_used($before,$after) {
return (substr($after,11)-substr($before,11))
+(substr($after,0,9)-substr($before,0,9));
}
?>
For further information, the script itself, etc, see http://edorfaus.xepher.net/div/convert-method-test.php


knetknight

md5(microtime()) is probably a fine method for low security or temporary passwords but I wouldn't use it for anything critical because the pattern is absolutely predictable. e.g. If I have an idea of the time frame in which the password was generated in this manner it'd be a simple matter to write a script that generates all possible md5sums for microtime() within' that frame. The less sure I am of when the password was generated the bigger my list would have to be but you get the idea.

yonman

md5 time stamps can be further hardened by appending a "secret predefined key" (i.e, one that is stored in a hardened position ... a sort of poor man's bi-directional encryption key) after the timestamp, before passed into the md5 function.
a 40-characters long key can seriously hinder the brute force attack described above. Wouldn't use this method for anything really important though ... unless backed up by more layers for defense.


elsand

kayode's implementation of randomString() generates predictable data (digit,letter,digit,letter,digit,...) and thus shouldn't be used for anything sensitive like transaction ids.
See uniqid() for this kind of functionality.
If you insist on rolling your own, you'd could do something like:
<?
function rstr($len) {
$i = 0;
$str = "";
while ($i++ < $len) $str .= chr(rand(33,126));
return $str;
}    
echo rstr(16);
// Outputs: q$lUY*Q1"1U%>+wi
?>
   
This generates a string of chars from the printable range of ascii chars.
To get a random hex-string, do something like:
<?
function rstr($len) {
$i = 0;
$str = "";
while ($i++ < $len) $str .= dechex(rand(0,15));
return $str;
}    

   
echo rstr(16);
// Outputs: 4f1f8c95514db8dd
?>


me

Just to say that what "junk" said about using the timestamp for indexes does make sense in some situations.  For instance, I have a deliverables management page that does 2 things:
1) FTP transfer of the file to the server.  This operation requires the file to be transfered to a directory specific to that one delivery
2) Create an entry in database with all the details of the delivery, including the filepath for download purposes.
If I wanted to use the auto increment function, there would be no way for me to know the index of the DB entry before actually doing the insert.  So to work consistently I would have to do:
DB insert -> Fetch the index value -> Try to upload the file -> if transfer fails: delete DB entry
With timestamp it would look like this:
Compute timestamp -> Try file transfer -> DB insert if transfer OK
The choice is yours I guess


d dot triendl

james at gogo dot co dot nz made a small mistake:
Here's the fixed one:
<?php
$floattime = (float) array_sum(explode(' ', microtime());
//or shorter
$floattime = array_sum(explode(' ', microtime()));
?>


floppie

It's pretty easy to know the value before you insert the new row.  You can either select the last row with:
<?php
// replace `id` with whatever you named your auto_increment field
$query = 'SELECT `id` FROM `table_in_question` ORDER BY `id` DESC LIMIT 0, 1';
if(!$sql = mysql_query($query)) {
die('Query failed near ' . __FILE__ . ':' . __LINE__);
}
list($id) = mysql_fetch_row($sql);
$next_id = $id + 1;
?>
And assume there are no breaks in the table.  If your application can safely ensure this, this is the simplest way to do it.  Or, if your application cannot ensure this, you can use this:
<?php
$query = 'SHOW TABLE STATUS LIKE \'table_in_question\'';
if(!$sql = mysql_query($query)) {
die('Query failed near ' . __FILE__ . ':' . __LINE__);
}
$row = mysql_fetch_row($sql);
$next_autoincrement = $row[10];
/* ----------------- OR --------------------- */
$row = mysql_fetch_array($sql);
$next_autoincrement = $row['Auto_increment'];
?>
Both work quite well.  I use the first in my game for certain insertions.


php

Interesting quirk (tested in PHP 5.0.3): You can get very wacky results from microtime when it is called in the destructor of an object at the end of a script. These times vary enormously and can be in the *past*, when compared to microtime calls in the body of the script.
As a case example, I played with a timer object that measured microtime when it was created at the start of the script, and measured microtime again at the end of the script using __destruct(); and then printed the total execution time (end time - start time) at the bottom of the page. On short scripts, this would often give a negative time!
This quirk does not appear if microtime is measured with an automatic shutdown function (using <?PHP register_shutdown_function('myfunc') ?>. Incidentally, the automatic shutdown functions are called after output buffers are flushed but before object destructors are called.


heavyraptor

Instead of using the complicated function below
<?php
function microtime_float() {
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}
?>
you may use my the fast & sexy function
<?php
function microtime_float() {
 return array_sum(explode(' ',microtime()));
}
?>
Returns the exactly same result.
have fun :)


aharsani

instead of suggested:
function microtime_float()
{
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}
i have to use:
function microtime_float()
{
   list($usec, $sec) = explode(" ", microtime());
   $fusec = (float)$usec;
   if($fusec > 0) {
      $fusec -= floor($fusec);
   }
   return $fusec + time();
}
reason:
microtime() randomly return time which is different then time() +-15sec...


no dot spam

In reply to "me at whereever dot com" below, this is what SQL transactions are for. There's is absolutely no reason to use the microtime as a DB index, unless it holds some intrinsic meaning to do so, ie. only when it makes sense to have the microtime as your (primary) key.

mcq

if you want to measure runtime of some code, and the result is really relevant, then keep in mind the followings:
1. you should only measure the time the code runs. This means if you use functions to make a double from microtime, then get begin time, run the code, get end time, and only _after_ this do conversion and computing. This is relevant for short cycles.
2. if runtime is very small, you can put the code in a loop and run it for 100 or 1000 times. The more you run it the more accurate the value will be. Do not forget to divide the runtime by the times you ran it.
3. if you are measuring a loop, then you do not actually measure the runtime of one cycle. Some caching may occur which means you will not get one cycle's runtime. For a short code, this can eventually result in big differences. Use looping only if the code is long and comlicated.
4. your runtime will be highly affected by the load of the server, which may be effected by many things - so, always run your runtime measuering multiple times, and, when comparing two methods, for e.g., then measure their runtimes one after the other, so I mean do not use values from yesterday, the circumstances may strongly affect your measuring.
Trapeer


sneskid

I've noticed when running microtime() for the first time, there is a bit of a delay (v 5.1.4).
Try this:
<?php
function stuff() {
$t1 = microtime(true);
$t2 = microtime(true);
echo sprintf('%.6f', ($t2 - $t1) ) . "\r\n";
}
//microtime();
stuff();
stuff();
stuff();
?>
The first result will probably be a little higher.
I get:
0.000004
0.000001
0.000001
Then try calling microtime() just once before the stuff()s.
The first run will drop by a bit.
Don't forget sprint() can format your numbers.


lacent

i've made several timer functions, and different methods of how to check time, for loading and benchmarking and such. this class works pretty good for whatever you might need it for. start it, then use stopwatch::now() to check time at that moment. it doesn't affect the start time so you can check the loadtime at that moment several times within your script, or run multiple stopwatches.
<?php
class stopwatch
{
private $round = 3;

function __construct ( )
{
$this->start = microtime();
}

function now ( )
{
$start = $this->math($this->start);
$now = $this->math();
return round($now - $start, $this->round);
}
function math ($time = FALSE)
{
if ( !$time ) $time = microtime();
$temp = explode(' ', $time);
return $temp[0] + $temp[1];
}

}
?>
usage:
$stopwatch = new stopwatch();
/* some code */
echo $stopwatch->now();


sybeer dot superspamkiller

I write two line script generation time code (inspirated by samples above):
<?php
$startTime = array_sum(explode(" ",microtime()));
<<some php code>>
echo round((array_sum(explode(" ",microtime())) - $startTime),4).' sec';
// number four tell how many digits will be print
?>
example code execution reslults
0.4983 sec
<>


kayode muyibi

I use this for unique transactional ids.
function randomString($randStringLength)
{
$timestring = microtime();
$secondsSinceEpoch=(integer) substr($timestring, strrpos($timestring, " "), 100);
$microseconds=(double) $timestring;
$seed = mt_rand(0,1000000000) + 10000000 * $microseconds + $secondsSinceEpoch;
mt_srand($seed);
$randstring = "";
for($i=0; $i < $randStringLength; $i++)
{
$randstring .= mt_rand(0, 9);
$randstring .= chr(ord('A') + mt_rand(0, 5));
}
return($randstring);
}


alreece45

I ran my own tests based on five of the functions here to emulate the PHP5 behavior on PHP4. As always, these aren't needed on PHP5, but I was intrested in which one would run most quickly.
My results are as follows:
Function 1 (example): performs at 1x for these results
Function 2 (posted by yhoko): performs at about 1.033x
Function 3 (posted by james): performs at about 1.031x
Function 4 (posted by emuxperts admin/m0sh3) performs at about 0.945x
Function 5 (posted by  Z0d): performs at about 1.103x
So if you're  concerned about peformance, consider the use of the strtok() function as Z0d used. Most of us, however, aren't going to need that sort of speed in a microtime function. In a test of 1 million iterations, it saved about 1.3 seconds. I'm not sure of many php applications that would use microtime that extensively. If so, how many of those microtimes is the float value actually needed.
I ran this test many times in different orders (modify the $functions var) and many times.
Here is the output I used for these results:
Function [float_microtime_1] Total Time: 13.6581590175628662
Function [float_microtime_1] Average Time: 0.0000136581590176
Function [float_microtime_2] Total Time: 13.2114200592041016
Function [float_microtime_2] Average Time: 0.0000132114200592
Function [float_microtime_3] Total Time: 13.2385060787200928
Function [float_microtime_3] Average Time: 0.0000132385060787
Function [float_microtime_4] Total Time: 14.4395959377288836
Function [float_microtime_4] Average Time: 0.0000144395959377
Function [float_microtime_5] Total Time: 12.3734378814697266
Function [float_microtime_5] Average Time: 0.0000123734378815
Here's my test script:
<?php
function float_microtime_1() {

list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);

}

function float_microtime_2() {

$time = microtime();
return (double)substr( $time, 11 ) + (double)substr( $time, 0, 8 );

}

function float_microtime_3() {

return array_sum(explode(' ',microtime()));

}
function float_microtime_4() {
return (float)preg_replace('#^0\.([0-9]+) ([0-9]+)$#', '\2.\1', microtime());
}

function float_microtime_5() {

return strtok(microtime(), ' ') + strtok('');

}

// settings for benchmark.
$functions = array(
'float_microtime_5',
'float_microtime_1',
'float_microtime_2',
'float_microtime_3',
'float_microtime_4',
);

$amount = 1000000;
set_time_limit(0);

// actual benchmark

$count = count($keys);

if($count > 0) {

// first get the functions in memory or w/e... sortof
foreach($functions as $function) {
$value = $function();

}

// run the test

foreach($functions as $function) {

$times = $amount;

$start[$function] = microtime();

while(--$times) {

$value = $function();

}

$stop[$function] = microtime();

}

foreach($functions as $function) {

$start_time = strtok($start[$function], ' ') + strtok('');
$stop_time = strtok($stop[$function], ' ') + strtok('');
$total_time = $stop_time - $start_time;
$average_time = $total_time / $amount;

echo 'Function [' . $function . '] Total Time: ' . number_format($total_time, 16) . chr(10);
echo 'Function [' . $function . '] Average Time: '.  number_format($average_time, 16) . chr(10);
}
}

else {

echo 'No Tests to run.';

}
?>


ed

I personally use the following class, created by myself, to record page creation time.
<?php
class Timer {
// Starts, Ends and Displays Page Creation Time
function getmicrotime() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}

function starttime() {
$this->st = $this->getmicrotime();
}

function displaytime() {
$this->et = $this->getmicrotime();
return round(($this->et - $this->st), 3);
}
}
?>
Called by doing the following
<?php
$time = new Timer;
$time->starttime();
// The rest of your script
echo 'Script took '.$time->displaytime().' seconds to execute'
?>


pizza23

I needed a way to give the total time to execute a whole page of code that included MySQL code as well and the exmples show did not quite help, Althought they lead me to the answer.
<?PHP
$starttimer = time()+microtime();
/*
...Page of Code
...MySQL Code
*/
$stoptimer = $time+microtime();
$timer = round($stoptimer-$starttimer,4);
echo "Page created in $timer seconds.";
?>
Result:
Page created in 4.1368 seconds.


vladson

I like to use bcmath for it
<?php
function micro_time() {
$temp = explode(" ", microtime());
return bcadd($temp[0], $temp[1], 6);
}
$time_start = micro_time();
sleep(1);
$time_stop = micro_time();
$time_overall = bcsub($time_stop, $time_start, 6);
echo "Execution time - $time_overall Seconds";
?>


08-apr-2005 05:07

I like more this way of presenting the microtime:
<?php
function utime(){
$time = microtime();
return substr($time, 11, 10).substr($time, 1, 7);
}
print utime(); // 1112975697.842941
?>
Sweet short string :)


16-feb-2006 04:07

i hope everyone who reads junk at plaino dot com's comment realizes how stupid that is. sql has a built-in auto-increment-function for indexes which I'm sure is much more optimized, easier to understand and lastly it makes more sense than using a number like that =/

unluckypixie

I don't know why no-one else has suggested this, but clearly the easiest way to replicate the PHP5 behaviour is to do:
$mtime = array_sum(explode(" ",microtime()));
I challenge anyone to write it shorter and neater than that ;o)


m0sh3

Hey, check this out =]
$mtime = (float)preg_replace('#^0\.([0-9]+) ([0-9]+)$#', '\2.\1', microtime());


exaton

Here's what I use to time my scripts.
There's a bit of surrounding code in the function, which will induce errors in short cycles ; this should therefore be used in repetitive context where the error will be amortized (cf. also mcq at supergamez dot hu 's comment below).
Note however that the important thing, $now = microtime(TRUE), happens at the very beginning, not suffering from any extraneous delay, and following it at the chronometer start is only one little condition, and a particularly compiler-friendly one at that (I think).
Hope this does not turn out too ugly after wordwrap()...
/************************************************************
*
* void | float chronometer()
*
* Enables determination of an amount of time between two points in a script,
* in milliseconds.
*
* Call the function a first time (as void) to start the chronometer. The next
* call to the function will return the number of milliseconds elapsed since
* the chronometer was started (rounded to three decimal places).
*
* The chronometer is then available for being started again.
*
************************************************************/
$CHRONO_STARTTIME = 0;
function chronometer()
{
global $CHRONO_STARTTIME;

$now = microtime(TRUE);  // float, in _seconds_

if ($CHRONO_STARTTIME > 0)
{
/* Stop the chronometer : return the amount of time since it was started,
in ms with a precision of 3 decimal places, and reset the start time.
We could factor the multiplication by 1000 (which converts seconds
into milliseconds) to save memory, but considering that floats can
reach e+308 but only carry 14 decimals, this is certainly more precise */

$retElapsed = round($now * 1000 - $CHRONO_STARTTIME * 1000, 3);

$CHRONO_STARTTIME = 0;

return $retElapsed;
}
else
{
// Start the chronometer : save the starting time

$CHRONO_STARTTIME = $now;
}
}


nrixham

here's an ultra simple script for you all (PHP5 only.. for obvious reasons)
stick this at the top of any script or app, and you'll get a the execution time in microseconds of the script.
It will output in raw text at the foot of the output, after execution has finished.. so only really useful for developing (swap the print_r for a logging function for live use?)
<?
class pageExecutionTimer {
private $executionTime;

public function __construct() {
$this->executionTime = microtime(true);
}

public function __destruct() {
print_r(chr(10).chr(13).(microtime(true)-$this->executionTime));
}
}
$pageExecutionTimer = new pageExecutionTimer();
?>


junk

Here's a quick function to output a unique number. Good for MySQL / SQL idexes and unique id values.
function uniqueTimeStamp_float(){
  $Asec = explode(" ", microtime());
  $Amicro = explode(".", $Asec[0]);
  return ($Asec[1].".".substr($Amicro[1], 0, 4));
}
print (uniqueTimeStamp_float());
// outputs a unique something like:
// 1136849268.0180
function uniqueTimeStamp(){
  $Asec = explode(" ", microtime());
  $Amicro = explode(".", $Asec[0]);
  return ($Asec[1].substr($Amicro[1], 0, 4));
}
print (uniqueTimeStamp());
// outputs a unique something like:
// 11368492680180


d dot schneider

Here the short way.
<?
$floattime = array_sum(explode(chr(32), microtime()));
?>


blagovest dot buyukliev

Here is a very short and compact way to determine the execution time of a script in seconds, in just two lines:
$tm_start = array_sum(explode(' ', microtime()));
...
$secs_total = array_sum(explode(' ', microtime())) - $tm_start;
Very handy for debugging and testing purposes.


webmaster

Here is a small script I made so that I would not have to deal with vars.  All you have to do is run the function twice and the second time run, it will echo the runtime.  If you place a number in the last function "script_runtime(5)" it will round off the number to that decimal place.
<?php
function script_runtime ( $round = 20 ) {
         //Check to see if the global is already set
         if ( !empty( $GLOBALS['start_script_runtime'] ) ) {
                   //The global was set. So, get the current microtime and explode it into an array.
                   list($msec, $sec) = explode(" ", microtime());
                   echo round(($sec + $msec) - $GLOBALS['start_script_runtime'], $round);
         } else {
                   // The global was not set. Create it!
                   list($msec, $sec) = explode(" ", microtime());
                   $GLOBALS['start_script_runtime'] = $sec + $msec;
         }
}
// Example:
script_runtime();
sleep(1);
script_runtime();
?>


edwardzyang

Here is a modified version of the chronometer functions. It acts like a "lap watch", immediately starting another timing session right after you call it. It also lets you specify the return value to be in seconds or in milliseconds: this is useful when a microsecond() timing would return a negative value.
<?php
/*
* Slightly modified from http://www.php.net/manual/en/function.microtime.php, adds
* support for Second values (as microtime can cause problems when you run extended loops).
* It also is "unstopped" timing, that is, the timer never sleeps.
*/
$CHRONO_STARTTIME = 0;
define("RET_TIME", "ms"); //Can be set to "ms" for milliseconds
or "s" for seconds
function chronometer()
{
  global $CHRONO_STARTTIME;
 
  $now = microtime(TRUE);  // float, in _seconds_
 
  if (RET_TIME === 's') {
  $now = $now + time();
  $malt = 1;
  $round = 7;
  } elseif (RET_TIME === 'ms') {
  $malt = 1000;
  $round = 3;
  } else {
  die("Unsupported RET_TIME value");
  }
 
  if ($CHRONO_STARTTIME > 0) {
      /* Stop the chronometer : return the amount of time since it was started,
      in ms with a precision of 3 decimal places, and reset the start time.
      We could factor the multiplication by 1000 (which converts seconds
      into milliseconds) to save memory, but considering that floats can
      reach e+308 but only carry 14 decimals, this is certainly more precise */
     
      $retElapsed = round($now * $malt - $CHRONO_STARTTIME * $malt, $round);
     
      $CHRONO_STARTTIME = $now;
     
      return $retElapsed;
  } else {
      // Start the chronometer : save the starting time
     
      $CHRONO_STARTTIME = $now;
     
      return 0;
  }
}
?>
It can be used like this:
<?php
chronometer();
//Do stuff;
echo chronometer(); //this will return the time taken to "Do stuff"
//Do more stuff
echo chronometer(); //this will return the time taken to "Do more stuff"
?>


david genord ii

Here is a little more versitile version of the chronometer script below.
/************************************************************
*
*    void | float chronometer($timer)
*
*    Works exactly like a stop watch, ie. starts if stopped
*    and stops if started
*
*    Call the function a first time to start the chronometer.
*    The next call to the function will return the number of
*    milliseconds elapsed since the chronometer was started
*    (rounded to three decimal places). The next call
*    will start the chronometer again from where it finished.
*
*    Multiple timers can be used by creating multiple $timer
*    variables.
*
*    An example script would be:
*    
*    chronometer($timer1);
*    DO STUFF HERE
*    chronometer($timer2);
*    chronometer($timer3);
*    DO MORE STUFF
*    echo chronometer($timer1);
*    DO SOMETHING
*    echo chronometer($timer3);
*    DO SOMETHING
*    echo chronometer($timer2);
*
*    The timer variables do not need to be declared or
*    initialized before use
*
************************************************************/
function chronometer(&$CHRONO_STARTTIME)
{
  $now = microtime(TRUE);  // float, in _seconds_
 
  if(isset($CHRONO_STARTTIME['running']))
  {
  if($CHRONO_STARTTIME['running'])
  {
  /* Stop the chronometer : return the amount of time since it was started,
  in ms with a precision of 3 decimal places.
  We could factor the multiplication by 1000 (which converts seconds
  into milliseconds) to save memory, but considering that floats can
  reach e+308 but only carry 14 decimals, this is certainly more precise */
 
  $CHRONO_STARTTIME['elapsed'] += round($now - $CHRONO_STARTTIME['temp'], 3);
  $CHRONO_STARTTIME['running'] = false;
 
  return $CHRONO_STARTTIME['elapsed'];
  }
  else
  {
  $CHRONO_STARTTIME['running'] = true;
  $CHRONO_STARTTIME['temp'] = $now;
  }
  }
  else
  {
      // Start the chronometer : save the starting time
     
  $CHRONO_STARTTIME = array();
  $CHRONO_STARTTIME['running'] = true;
  $CHRONO_STARTTIME['elapsed'] = 0;
      $CHRONO_STARTTIME['temp'] = $now;
  }
}


e dot nijssen

here is a handy script generation time code example(scrabble):
<?php
#put this in the very beginning
$timestart = microtime();
<<some code>>
#put this in the very end
$timeend = microtime();
$diff = number_format(((substr($timeend,0,9)) + (substr($timeend,-10)) - (substr($timestart,0,9)) - (substr($timestart,-10))),4);
echo "
<small><small>script generation took $diff s </small></small>";
?>
this code will give you the time the <<some code>> took to evaluate in 4 decimals, if you want more or less decimals, edit the last parameter in the line that defines $diff.


doom_quake

heavyraptor,
Optimization should consider two things:
1. The order in which the functions are called (due to load time, and processor prefetch)
2. The number of tests involved (10 is not enough)
I would try the test with 10,000 iterations and once with function 1 called first and once with function 2 called first.
If possible, try not to store results in an array (since this step will get slower as time passes), but rather process them inline.  This can be done by storing the min and max time difference between the two functions then comparing and overwriting if the current value is smaller/larger.
Also consider an average difference by adding the current time difference each time then dividing by the number of iterations.  This will give you a more accurate picture of the true speed benefit.


martijn

For highly accurate performance timing of an algorithm, you'll need to take into account the time it takes to run microtime() and/or a replacement function such as the microtime_float.
Make sure to keep all calculations outside the timers.
Here's a small sample. Please note that it takes into account the assignment of one variable as well during calibration, since this will happen in the actual test as well.
$calibrate_begin = microtime_float();
$calibrate_end = microtime_float();
$overhead_time = $calibrate_end - $calibrate_begin;
$performance_begin = microtime_float();
// test
$performance_end = microtime_float();
$result_time = ($performance_end - $performance_begin) - $overhead_time;
For even more accuracy in testing, loop the ENTIRE code a number of times. If you just loop the calibration and test independantly, you'll get misleading results due to time spent running the loop codes themselves.


eric pecoraro

Even though this function uses gettimeofday(), it fits better here. I created it to provide unique IDs for image names that were being process in a fast loop scenario.
<?php
// 15 Digit Microtime Stamp (returns a 15 digit timestamp/unique id inside loops)
// Inspired by Christian Wenz's excellent "PHP Phrasebook".
function microtimestamp($id='') {
$stamp = gettimeofday();
// id insures unique id in fast loops, no id is in sync w/ PHP's time() function
if ($id=='id') { $divby=100000; } else { $divby=1000000; }
$stamp = $stamp['sec'] + $stamp['usec'] / $divby ;
$stamp = str_replace('.','',$stamp);
$stamp = substr($stamp.'00000',0,15) ; // for consistent length
return $stamp;  
}
// TESTS
// synced with time() function
echo '<b>'.time()." <- time()</b>
\n";
while ( $cnt < 11 ) {
$cnt++;
echo microtimestamp() . "
\n";
}
// adds a few random seconds to time() ... but produces unique ids in fast loop
echo "<b>Unique IDs</b>
\n";
while ( $cnt2 < 11 ) {
$cnt2++;
echo microtimestamp('id') . "
\n";
}
?>


sergey89

Casually to not change saved time of start data it is possible to keep in session.
<?php
   //$start_time = microtime(true);
   $_SESSION['start_time'] = microtime(true);
   function execute_time() {
       return (microtime(true) - $_SESSION['start_time']);
   }
   ////some code
   ////change saved time
   //$start_time = time();
   ////some code
   printf('Execute time: %.5f', execute_time());
?>


heavyraptor

By the way, I forgot to post my microtime_float() test results.
Here's my script:
<?php
error_reporting(E_ALL);
header('Content-type: text/plain');
function microtime_float1() {
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}
function microtime_float2() {
 return array_sum(explode(' ',microtime()));
}
// Init
for ($i = 0; $i < 10; $i++)
 microtime();
$ms1 = array();
$me1 = array();
$ms2 = array();
$me2 = array();
for ($i = 0; $i < 10000; $i++) {
 // microtime_float1()
 $ms1[] = microtime();
 microtime_float1();
 $me1[] = microtime();
 for ($j = 0; $j < 4; $j++)
   microtime();
 // microtime_float2()
 $ms2[] = microtime();
 microtime_float2();
 $me2[] = microtime();
}
// Parse time
foreach ($ms1 as $k => $time) $ms1[$k] = array_sum(explode(' ',$time));
foreach ($me1 as $k => $time) $me1[$k] = array_sum(explode(' ',$time));
foreach ($ms2 as $k => $time) $ms2[$k] = array_sum(explode(' ',$time));
foreach ($me2 as $k => $time) $me2[$k] = array_sum(explode(' ',$time));
// Calculate average
$ms1 = array_sum($ms1) / count($ms1);
$me1 = array_sum($me1) / count($me1);
$ms2 = array_sum($ms2) / count($ms2);
$me2 = array_sum($me2) / count($me2);
echo 'microtime_float1() ' . number_format($me1 - $ms1,10) . "\n";
echo 'microtime_float2() ' . number_format($me2 - $ms2,10);
?>
This script calculates the used time by microtime_float1() and microtime_float2().
I get the following results as the biggest differences:
microtime_float1() 0.0000882149
microtime_float2() 0.0000278950
... and these as lowest differences:
microtime_float1() 0.0000467300
microtime_float2() 0.0000417233
of course this may change everytime you reexecute the script. The differences are very little, but this may be important in some scripts.
Result:
As you see, my microtime_float() function is better :D
Anyway, this is all kind of nonsense, because most of the people use PHP 5 and there we just use microtime(true), which gives us the same result as my microtime_float().
So if you're using PHP < 5, use this function below:
<?php
function microtime_float() {
 return array_sum(explode(' ',microtime()));
}
?>
Thank you for your attention, have fun :).
... and sorry because of my bad english.


joelatlearnossdotcom

A simpler page execution script would be the following:
<?php
echo ("Page executed in ");
$execute = microtime();
print (number_format($execute,4));
echo (" seconds.");
?>
// prints out following:
Page executed in 0.5364 seconds.


saphir

A simple class in PHP5 allowing to know the execution time of a script :
<?php
class Timer
{
private $m_Start;
public function __construct()
{
$this->m_Start = 0.0;
}
private function GetMicrotime()
{
list($micro_seconds, $seconds) = explode(" ", microtime());
return ((float)$micro_seconds + (float)$seconds);
}
public function Init()
{
$this->m_Start = $this->GetMicrotime();
}
public function GetTime($Decimals = 2)
{
return number_format($this->GetMicrotime() - $this->m_Start, $Decimals, '.', '');
}
}
$MyTimer = new Timer();
$MyTimer->Init();
sleep(1);
echo $MyTimer->GetTime();
// Output result -> 1.00
?>
Nico.


radek

A lot of the comments here suggest adding in the following way:  (float)$usec + (float)$sec
Make sure you have the float precision high enough as with the default precision of 12, you are only precise to the 0.01 seconds.  
Set this in you php.ini file.
       precision    =  16


emre

A little modification to the Timer class by ed [at] twixcoding [dot] com. With this class you can pause and unpause the timer and selectively exclude certain areas of your code from the total time.
<?php
class Timer {
var $s;
var $p = 0;
function start() {
$this->s = $this->getmicrotime();
}
function pause() {
$this->p = $this->getmicrotime();
}
function unpause() {
$this->s += ($this->getmicrotime() - $this->p);
$this->p = 0;
}
function fetch($decimalPlaces = 3) {
return round(($this->getmicrotime() - $this->s), $decimalPlaces);
}
function getmicrotime() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
}
// ------------------- TEST ----------------------------
$t = new Timer();
$t->start();
sleep(1);
var_dump($t->fetch()); // Outputs: float(0.999)
$t->start();
$t->pause();
sleep(1);
$t->unpause();
var_dump($t->fetch()); // Outputs: float(0)
// ------------------------------------------------------
?>


jj

A 14 digit unique timestamp
function uniqueTimeStamp() {
 $milliseconds = microtime();
 $timestring = explode(" ", $milliseconds);
 $sg = $timestring[1];
 $mlsg = substr($timestring[0], 2, 4);
 $timestamp = $sg.$mlsg;
 return $timestamp;
}
echo uniqueTimeStamp();


yhoko

@heavyraptor
Try this one, too:
<?php
function microtime_float()
{
$time = microtime();
return (double)substr( $time, 11 ) + (double)substr( $time, 0, 8 );
}
?>
Yhoko


28-sep-2004 07:45

3. if you are measuring a loop, then you do not actually measure the runtime of one cycle. Some caching may occur which means you will not get one cycle's runtime. For a short code, this can eventually result in big differences. Use looping only if the code is long and comlicated.
4. your runtime will be highly affected by the load of the server, which may be effected by many things - so, always run your runtime measuering multiple times, and, when comparing two methods, for e.g., then measure their runtimes one after the other, so I mean do not use values from yesterday, the circumstances may strongly affect your measuring.
Trapeer


t0russ

<?php
/*
compares runtimes of 2 functions
to use, copy/paste functions, and call them from fct1 and fct2
coded by t0rus
*/
function stripQuotes1($st){
while(($k=strpos($st,'"'))!==false)
$st=substr($st,0,$k).substr($st,$k+1);
while(($k=strpos($st,'\''))!==false)
$st=substr($st,0,$k).substr($st,$k+1);
return $st;
}
function stripQuotes2($str){
for($i=0;$i<strlen($str);$i++)
if (($str{$i}==="'")||($str{$i}==='"')){ // === gave better results than ==
$str=substr($str,0,$i).substr($str,$i+1);
$i--;
}
return $str;
}
$runtimes=1000;//how many times to run the tests
function fct1(){
stripQuotes1('01abba6"78901\' 1234""12345678\"123-"""3\'\'2');
}
function fct2(){
stripQuotes2('01abba6"78901\' 1234""12345678\"123-"""3\'\'2');
}
//################################################################//
$time1=0;
for ($i=0;$i<$runtimes;$i++){
$time_start = array_sum(explode(' ', microtime()));
fct1();
$time_end = array_sum(explode(' ', microtime()));
$time1 = ($time1*$i+$time_end - $time_start)/($i+1);
}
echo "\nfct1 runs in $time1 ms.\n";
$time2=0;
for ($i=0;$i<$runtimes;$i++){
$time_start = array_sum(explode(' ', microtime()));
fct2();
$time_end = array_sum(explode(' ', microtime()));
$time2 = ($time2*$i+$time_end - $time_start)/($i+1);
}
echo "\nfct2 runs in $time2 ms.\n";
$tf = round($time2/$time1);
echo "\nfct".(($tf>1)?'1 is faster by a factor of '.$tf:(($tf<1)?'2 is faster by a factor of '.round($time1/$time2):'1 is roughly equal to fct2'))."\n\n";
?>
Sample output:
fct1 runs in 0.00017227101325989 ms.
fct2 runs in 0.0010822315216064 ms.
fct1 is faster by a factor of 6


16-aug-2005 11:06

<?php
/**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float()
{
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
// Sleep for a while
usleep(100);
$time_end = microtime_float();
//*****
//***** Use round with 4 spaces after the decimal for shorter times. The output would be 0.003 seconds
//*****
$time = round($time_end - $time_start, 4);
echo "Did nothing in $time seconds\n";
?>


adiwicaksono

<?
function uniqueTimeStamp(){
  $Asec   = explode(" ", microtime());
  $Amicro = explode(".", $Asec[0]);
  return ($Asec[1].substr($Amicro[1], 0, 4));
}
for($i = 0; $i < 10000; $i++){
       print (uniqueTimeStamp());
       print "\n";
}
?>
uniqueTimeStamp() is not Unique :)
Try this instread
$idmessage  = substr(substr(uniqid(mktime(),4),16),0,8);
Unique


Change Language


Follow Navioo On Twitter
checkdate
date_create
date_date_set
date_default_timezone_get
date_default_timezone_set
date_format
date_isodate_set
date_modify
date_offset_get
date_parse
date_sun_info
date_sunrise
date_sunset
date_time_set
date_timezone_get
date_timezone_set
date
getdate
gettimeofday
gmdate
gmmktime
gmstrftime
idate
localtime
microtime
mktime
strftime
strptime
strtotime
time
timezone_abbreviations_list
timezone_identifiers_list
timezone_name_from_abbr
timezone_name_get
timezone_offset_get
timezone_open
timezone_transitions_get
eXTReMe Tracker