PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

mktime> <localtime
Last updated: Fri, 16 May 2008

view this page in

microtime

(PHP 4, PHP 5)

microtime — Return current Unix timestamp with microseconds

Description

mixed microtime ([ bool $get_as_float ] )

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

Parameters

get_as_float

When called without the optional argument, this function returns the string "msec sec" where sec is the current time measured in the number of seconds since the Unix Epoch (0:00:00 January 1, 1970 GMT), and msec is the microseconds part. Both portions of the string are returned in units of seconds.

If the optional get_as_float is set to TRUE then a float (in seconds) is returned.

ChangeLog

Version Description
5.0.0 The get_as_float parameter was added.

Examples

Example #1 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 #2 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";
?>

See Also



mktime> <localtime
Last updated: Fri, 16 May 2008
 
add a note add a note User Contributed Notes
microtime
carbolymer at o2 dot pl
10-May-2008 02:22
to: blue at ba7rain dot net

Instead of:
<?php
function GetMicro(){
        list(
$usec, $sec) = explode(" ", microtime());
        return ((float)
$usec + (float)$sec);
}
?>

You can simply use:
<?php
microtime
(true);
?>

Which gives the same effect. I don't know why that argument is not mentioned here.
Example:
<?php
$i
= microtime(true);
sleep(1);
echo
microtime(true)-$i;
/*
-- output --
0.99996805191
-- output --
*/
?>

Thanks to xk.
blue at ba7rain dot net
29-Mar-2008 09:29
I write this class for recording and keeping multiple records
with an optional separate function to display a flat number
without the confusing E-005, I have php<5.

<?php

class MicroRecord {
    var
$record = array();
    var
$irecord = array();
    function
MicroRecord(){
       
$time = $this->GetMicro();
       
//First one for training :)
       
$time = $this->GetMicro();
       
$this->itime = $time;
       
$this->start = $time;
    }
    function
GetMicro(){
        list(
$usec, $sec) = explode(" ", microtime());
        return ((float)
$usec + (float)$sec);
    }
    function
record($name=false,$ini=false){
       
$now = $this->GetMicro();
       
$time = $now - $this->start;
       
$ctime = $now - $this->itime;
        if ( (
$name === false) || ((string)$name == "" ) ){
           
$this->record[] = $time;
           
$this->irecord[] = $ctime;
        }
        else {
           
$this->record[(string)$name] = $time;
           
$this->irecord[(string)$name] = $ctime;
        }
       
$this->start = $now;
        if (!
$ini) {
            return
$time;
        }
        else {
            return
$ctime;
        }
    }
    function
display($name=false,$ini=false){
        if ( (
$name === false) || ((string)$name == "" ) ){
            if (!
$ini) {
                return
$this->record;
            }
            else {
                return
$this->irecord;
            }
        }
        else {
            if ( isset(
$this->record[(string)$name]) ){
                if (!
$ini) {
                    return
$this->record[(string)$name];
                }
                else {
                    return
$this->irecord[(string)$name];
                }
            }
        }
    }
}

function
longfloat($n){
   
$s="/([\-]|[\+])?(\d+)[\.]?(\d+)?[E]([\-]|[\+])(\d+)/i";
    if (
preg_match($s,$n,$m)){
       
$m[1] = ( ($m[1] == "-") ? "-" : "" );
       
$i = strlen($m[2]);
        if ( (
$m[4] == "-") && ($i > (int)$m[5]) ){
           
$part1 = substr($m[2].$m[3],0,$i-(int)$m[5]);
           
$part2 = substr($m[2].$m[3],$i-(int)$m[5]);
           
$result = $m[1].$part1.".". $part2;
        }
        else {
           
$zero = "";
            if (
$m[4] == "+"){
               
$j = strlen($m[3]);
               
$i = (int)$m[5] - ((int)$m[6] - $j);
            }
            for (
$i=$i; $i<(int)$m[5]; $i++) {
               
$zero .= "0";
            }
            if (
$m[4] == "-"){
               
$result = $m[1]."0.".$zero.$m[2].$m[3];
            }
            else {
                if (
$j > (int)$m[5] ) {
                   
$part1 = substr($m[3].$zero,0,(int)$m[5]);
                   
$part2 = substr($m[3].$zero,(int)$m[5]);
                   
$result = $m[1].$m[2].$part1.".". $part2;
                }
                else {
                   
$result = $m[1].$m[2].$m[3].$zero;
                }
            }
        }
    }
    elseif (
preg_match("/([\-]|[\+])?(\d+)[\.]?(\d+)?/i",$n,$m)){
       
$m[1] = ( ($m[1] == "-") ? "-" : "" );
       
$result = $m[1].$m[2].( (strlen($m[3]) > 0) ? ".".$m[3] : "" );
    }
    else {
       
$result = false;
    }
    return
$result;
}

print
"<pre>\r\n";
$micro = new MicroRecord();
//Recording the time for the first process.
print $micro->record();
print
"\r\n";
print
"\r\n";
//Calculate the second process time starting from the last record.
print $micro->record();
print
"\r\n";
print
"\r\n";
//Using optional longfloat() function to display long float number as a string.
//Calculate the time from the start/restart of MicroRecord().
//New Record from the start.
print ( longfloat($micro->record('one',true)) );
print
"\r\n";
print
"\r\n";
//Just Display the record from the start ('one',true).
print ( longfloat($micro->display('one',true)) );
print
"\r\n";
print
"\r\n";
//Time for this process only ('one').
print ( longfloat($micro->display('one')) );
print
"\r\n";
print
"\r\n";
//Time record array for each process.
print_r($micro->display());
print
"\r\n";
print
"\r\n";
//Time record array for the process from the begining of MicroRecord().
print_r($micro->display(false,true));
print
"\r\n";
print
"\r\n";
//Restart MicroRecord().
$micro->MicroRecord();
print
"\r\n";
print
"\r\n";
//First process record [0].
print ( longfloat($micro->record(false,true)) );
print
"\r\n";
print
"\r\n";
//Replacing the first record [0].
print ( longfloat($micro->record(0,true)) );
print
"\r\n";
print
"</pre>\r\n";

?>
Kirik
26-Feb-2008 09:51
Here is modified Fabian Otto code:

function processing_time($START=false)
{
    $an = 4;    // How much digit return after point

    if(!$START) return time() + microtime();
    $END = time() + microtime();
    return round($END - $START, $an);
}

How it's working? Wery simply! =)

Just call the function processing_time() in the begining of script, and put result in variable, then call this function again, but with $START param.. I show you, how you can use it..

Example:
<?php

// FUNCTIONS

function processing_time($START=false)
{
   
$an = 4;    // How much digit return after point

   
if(!$START) return time() + microtime();
   
$END = time() + microtime();
    return
round($END - $START, $an);
}

// MAIN SCRIPT

$START = processing_time();

/*

Here is our big-big code..

*/

$RESULT = processing_time($START);

echo
"Page created in $RESULT seconds.";
?>
That's it! =)
Kirik
26-Feb-2008 09:50
Here is modified Fabian Otto code:

function processing_time($START=false)
{
    $an = 4;    // How much digit return after point

    if(!$START) return time() + microtime();
    $END = time() + microtime();
    return round($END - $START, $an);
}

How it's working? Wery simply! =)

Just call the function processing_time() in the begining of script, and put result in variable, then call this function again, but with $START param.. I show you, how you can use it..

Example:
<?php

// FUNCTIONS

function processing_time($START=false)
{
   
$an = 4;    // How much digit return after point

   
if(!$START) return time() + microtime();
   
$END = time() + microtime();
    return
round($END - $START, $an);
}

// MAIN SCRIPT

$START = processing_time();

/*

Here is our big-big code..

*/

$RESULT = processing_time($START);

echo
"Page created in $RESULT seconds.";
?>
That's it! =)
ifoundthetao at gmail dot com
04-Feb-2008 08:55
Here is my first object.  I made a stopwatch that I think is pretty neat.  It uses the microtime setting with the floating point enabled.  I spent a lot of time working with the other version until it dawned on me that it is accurate to the thousandth of a second which is good enough for all of the sites that I will be working on for the time being.

<?php
//Details:
//       Started            Stopped
//   ---------------------------------------
// |        0          |          0          |    = Has not been used yet, or has been reset
//   ---------------------------------------
// |        0          |          1          |    = Holding time, but paused
//   ---------------------------------------
// |        1          |          0          |    = Currently running
//   ---------------------------------------
class Stopwatch {
   
    public function
__construct() {
       
$this->started = $this->stopped = $this->timer=0;
    }
   
    public function
Start() {
       
//leave the function because it is already running
       
if($this->started) return;
        if(!(
$this->stopped)) {
           
$this->started = true;
           
$this->timer = microtime(true);
        }
       
//stopwatch is currently stopped, begin tracking time again
       
if($this->stopped) {
           
$this->timer = microtime(true) - $this->timer;
           
$this->started = true;
           
$this->stopped = false;
        }
    }

    public function
Stop() {
       
//make sure that it is running before you stop it
       
if(!$this->stopped && $this->started) {
           
$this->timer = microtime(true) - $this->timer;
           
$this->stopped = true;
           
$this->started = false;
        }
    }
   
    public function
Reset() {
       
$this->timer = $this->started = $this->stopped = false;
    }
   
    public function
Display() {
       
//still running, use current time.
       
if(!($this->stopped) && ($this->started)) $sec = microtime(true) - $this->timer;
        else if(!
$this->stopped && !$this->started) $sec = 0;
        else
$sec = $this->timer;

        echo
"<br />Time: $sec seconds<br />";
    }

    private
$timer, $started, $stopped;
}
?>
Anonymous
26-Nov-2007 12:57
@zenofeller at zenofeller dot com:

I was trying to point out that randomString() significantly reduces the "randomness-per-byte" compared to what mt_rand() and friends gives you to begin with - eg. making it more "predictable".

If you're looking to generate hard-to-predict printable keys and cares about the length of the key (you perhaps need to stick in in a CHAR(32) field of some db-table), you'd be better off with either my rstr() or md5(uniqid(rand(), true)); which both will provide you with a much larger keyspace (and thus a smaller chance of a collision) in the same amount of bytes as randomString().

I should have said "more predictable" instead of just "predictable" in my previous post; you're indeed correct when you say that randomString() _will_ give you random data. It most definitely does, it just doesn't do so very effectively :)
helenadeus at gmail dot com
27-Oct-2007 06:39
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;
   
}
?>
zenofeller at zenofeller dot com
20-Oct-2007 10:13
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.
Elsand
12-Oct-2007 04:35
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

?>
blagovest dot buyukliev at dotscript dot com
31-Jul-2007 06:26
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.
kayode muyibi
30-Jun-2007 04:35
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);
    }
nrixham at gmail dot com
26-Jun-2007 04:24
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();
?>
Fabian Otto
15-Jun-2007 02:07
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.
pizza23 at yahoo dot com
13-Jun-2007 10:11
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.
alreece45 at yahoo dot com
02-Jun-2007 04:36
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.';
       
    }

?>
aharsani at gmail dot com
15-May-2007 03:26
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...
doom_quake at hotmail dot com
14-Jan-2007 07:51
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.
yhoko at yhoko dot com
19-Dec-2006 09:31
@heavyraptor

Try this one, too:

<?php
function microtime_float()
{
 
$time = microtime();
 return (double)
substr( $time, 11 ) + (double)substr( $time, 0, 8 );
}
?>

Yhoko
heavyraptor
08-Dec-2006 08:53
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.
heavyraptor
06-Dec-2006 10:15
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 :)
lacent at gmail dot com
15-Nov-2006 06:19
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();
sneskid at hotmail dot com
01-Nov-2006 10:13
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.
sergey89 at gmail dot com
04-Oct-2006 12:03
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());
?>
a dot winkelbauer at gmx dot at
16-Sep-2006 10:00
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;
}
?>
blade106NOSPAM at free dot fr
31-Aug-2006 03:44
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)
m0sh3 at hotmail dot com
23-Aug-2006 06:12
Hey, check this out =]

$mtime = (float)preg_replace('#^0\.([0-9]+) ([0-9]+)$#', '\2.\1', microtime());
admin at emuxperts dot net
20-Aug-2006 07:37
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
?>
emre [[at]] olmayan.org
31-May-2006 03:51
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)

// ------------------------------------------------------

?>
EdorFaus
16-May-2006 12:47
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
no dot spam at in dot my dot mail
16-May-2006 01:49
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.
Eric Pecoraro
30-Apr-2006 08:35
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><br>\n";
while (
$cnt < 11 ) {
   
$cnt++;
    echo
microtimestamp() . "<br>\n";
}
// adds a few random seconds to time() ... but produces unique ids in fast loop
echo "<b>Unique IDs</b><br>\n";
while (
$cnt2 < 11 ) {
   
$cnt2++;
    echo
microtimestamp('id') . "<br>\n";
}
?>
floppie at quadra-techservices dot com
16-Apr-2006 06:14
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[