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: Mon, 26 Nov 2007

view this page in

microtime

(PHP 4, PHP 5)

microtime — 返回当前 Unix 时间戳和微秒数

说明

mixed microtime ([ bool $get_as_float ] )

microtime() 当前 Unix 时间戳以及微秒数。本函数仅在支持 gettimeofday() 系统调用的操作系统下可用。

如果调用时不带可选参数,本函数以 "msec sec" 的格式返回一个字符串,其中 sec 是自 Unix 纪元(0:00:00 January 1, 1970 GMT)起到现在的秒数,msec 是微秒部分。字符串的两部分都是以秒为单位返回的。

如果给出了 get_as_float 参数并且其值等价于 TRUEmicrotime() 将返回一个浮点数。

Note: get_as_float 参数是 PHP 5.0.0 新加的。

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

参见 time()



mktime> <localtime
Last updated: Mon, 26 Nov 2007
 
add a note add a note User Contributed Notes
microtime
kpsimoulis [at] genatec
06-Jun-2008 03:53
This function is very useful for putting a start and end point in your page to find out where is the delay.

<?php

$start
= microtime(true);
// My source code here
$end = microtime(true);

echo
$end."-".$start."=".($end - $start). " seconds";

?>

If you try this example above (without any source code between the start and the end point). You will get an ugly value, something like:
1212690530.4132-1212690530.4132=8.1062316894531E-6 seconds

You will wonder why you get this because both numbers seem to be equal. Well this is because there is a hidden precision that we are not able to see.

To solve this problem I made a new function:

<?php

function my_microtime($precision = 4)
{
    return
round(microtime(true),4);
}

$start = microtime(true);
// My source code here
$end = microtime(true);

echo
$end."-".$start."=".substr(($end - $start),0,5). " seconds";

?>

It would be useful if they add another parameter for precision in this function or at least another boolean that will not include the hidden precision.
You can read more about the hidden precision in http://php.net/float
chris [at] dubcube.com
05-Jun-2008 12:58
this achieves moar of the desired effect i was seeking (i wanted decimal zeros, among other control factors).
<?php
$time
= date('YmdHis') + microtime(); //simple, no decimal control.
/*alternatively, if decimal adjustment desired needed:
$time = round(date('YmdHis') + microtime(), 3); //decimal control
*/

//print "$time </br>";
$strip = number_format ($time,2,'',''); // first '' is decimal indicator, second '' is thousandths sep/indicator (one char limit here).
print "$strip";
?>
Raza
01-Jun-2008 10:10
Here is a code that prints time taken by each step in a simple mySQL query.

<?php

function connect_database()
    {
       
$link = mysql_connect('www.mywebsite.com', 'db_local', 'password');
        if (!
$link)
            {
                   die(
'Could not connect: ' . mysql_error());
            }
       
mysql_select_db('db_local');
    }

function
disconnect_database()
    {
       
mysql_close();
    }

function
get_table()
    {
       
$sttime microtime(true);
       
connect_database();
       
$timediff = round((microtime(true) - $sttime)*1000, 2);
        print
"Connect: \t\t{$timediff} ms\n";

       
$query1 = "SELECT * FROM categories ";
       
$sttime microtime(true);
       
$table = mysql_query($query1);
       
$timediff = round((microtime(true) - $sttime)*1000, 2);
        print
"Query:  \t\t{$timediff} ms\n";

       
$sttime microtime(true);
       
disconnect_database();
       
$timediff = round((microtime(true) - $sttime)*1000, 2);
        print
"Disconnect:  \t{$timediff} ms\n";
        return
$table;
    }
   
$sttime microtime(true);
get_table();
$timediff = round((microtime(true) - $sttime)*1000, 2);
print
"Total:  \t\t{$timediff} ms\n";

/*
---------OUTPUT---------

Connect:        82.82 ms
Query:          14.55 ms
Disconnect:      0.09 ms
Total:          97.65 ms

*/

?>
Peter Kehl
30-May-2008 06:31
This function allows you to easily calculate time difference between two points in time without losing the precision.

<?php

   
/**    Calculate a precise time difference.
        @param string $start result of microtime()
        @param string $end result of microtime(); if NULL/FALSE/0/'' then it's now
        @return flat difference in seconds, calculated with minimum precision loss
    */
   
function microtime_diff( $start, $end=NULL ) {
        if( !
$end ) {
           
$end= microtime();
        }
        list(
$start_usec, $start_sec) = explode(" ", $start);
        list(
$end_usec, $end_sec) = explode(" ", $end);
       
$diff_sec= intval($end_sec) - intval($start_sec);
       
$diff_usec= floatval($end_usec) - floatval($start_usec);
        return
floatval( $diff_sec ) + $diff_usec;
    }

?>
luke at lucanos dot com
29-May-2008 07:48
Rather than using the list() function, etc. I have found the following code to be a bit cleaner and simpler:
<?php
$theTime
= array_sum( explode( ' ' , microtime() ) );
echo
$theTime;
# Displays "1212018372.3366"
?>
Anonymous
20-May-2008 05:55
to: carbolymer at o2 dot pl

Your example only works when you are using PHP >= 5.0.0. Previous versions don't have the optional get_as_float parameter.
carbolymer at o2 dot pl
10-May-2008 05: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
30-Mar-2008 12: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
27-Feb-2008 01: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
27-Feb-2008 01: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
05-Feb-2008 12: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
27-Nov-2007 04: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
28-Oct-2007 09: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
21-Oct-2007 01: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
13-Oct-2007 07: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 09: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 07: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
27-Jun-2007 07: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 05: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
14-Jun-2007 01: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
03-Jun-2007 07: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 06: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 11: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
20-Dec-2006 01:31
@heavyraptor

Try this one, too:

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

Yhoko
heavyraptor
09-Dec-2006 12: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
07-Dec-2006 02: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
16-Nov-2006 10: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
02-Nov-2006 02: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
05-Oct-2006 03: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
17-Sep-2006 01: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 06: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
24-Aug-2006 09:12
Hey, check this out =]

$mtime = (float)preg_replace('#^0\.([0-9]+) ([0-9]+)$#', '\2.\1', microtime());
admin at emuxperts dot net
21-Aug-2006 10: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 06: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();