microtime

(PHP 4, PHP 5, PHP 7)

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()

User Contributed Notes

johovich at yandex dot ru 06-Nov-2017 01:15
//Function to convert microtime return to human readable units
//функция для конвертации времени, принимает значения в секундах

function convert_time($time)
{
    if($time == 0 ){
        return 0;
    }
    //допустимые единицы измерения
    $unit=array(-4=>'ps', -3=>'ns',-2=>'mcs',-1=>'ms',0=>'s');
    //логарифм времени в сек по основанию 1000
    //берем значение не больше 0, т.к. секунды у нас последняя изменяемая по тысяче величина, дальше по 60
    $i=min(0,floor(log($time,1000)));

    //тут делим наше время на число соответствующее единицам измерения т.е. на миллион для секунд,
    //на тысячу для миллисекунд
    $t = @round($time/pow(1000,$i) , 1);
    return $t.$unit[$i];
}
how to set nonce value with microtime 18-Aug-2017 07:50
Using microtime() to set 'nonce' value:

ini_set("precision", 16);
$nonce="nonce=".microtime(true)/0.000001;
Daniel Rhodes 27-Aug-2013 09:54
But note that the default 'precision' setting of PHP* - which is used when a float is converted to a stringy format by echo()ing, casting or json_encode()ing etc - is not enough to hold the six digit accuracy of microtime(true).

Out of the box, microtime(true) will echo something like:

1377611450.1234

Which is obviously less than microsecond accuracy. You'll probably want to bump the 'precision' setting up to 16 which will echo something like:

1377611450.123456

*Internally* it will be accurate to the six digits even with the default 'precision', but a lot of things (ie. NoSQL databases) are moving to all-text representations these days so it becomes a bit more important.

* 14 at the time of writing
Nads 17-Jul-2013 05:28
Get date time with milliseconds

$micro_date = microtime();
$date_array = explode(" ",$micro_date);
$date = date("Y-m-d H:i:s",$date_array[1]);
echo "Date: $date:" . $date_array[0];

Test accuracy by running it in a loop.
Russell G. 04-May-2013 05:34
Note that the timestamp returned is "with microseconds", not "in microseconds". This is especially good to know if you pass 'true' as the parameter and then calculate the difference between two float values -- the result is already in seconds; it doesn't need to be divided by a million.
player27 16-Jan-2013 01:31
You can use one variable to check execution $time as follow:

<?php
$time
= -microtime(true);
$hash = 0;
for (
$i=0; $i < rand(1000,4000); ++$i) {
   
$hash ^= md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,10)));
}
$time += microtime(true);
echo
"Hash: $hash iterations:$i time: ",sprintf('%f', $time),PHP_EOL;
?>
thomas 12-Apr-2012 11:45
I have been getting negative values substracting a later microtime(true) call from an earlier microtime(true) call on Windows with PHP 5.3.8

Produces negative values
------------------------------
for($i = 0; $i<100; $i++) {
    $x =  microtime(true);
    //short calculation
    $y = microtime(true);
    echo ($y-$x) . "\n"; // <--- mostly negatives
}

Calling usleep(1) seems to work
---------------------------------------
for($i = 0; $i<100; $i++) {
    $x =  microtime(true);
    //short calculation
    usleep(1);
    $y = microtime(true);
    echo ($y-$x) . "\n"; // <--- fixed now
}
langpavel at phpskelet dot org 19-May-2011 10:46
I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible.

<?php
/**
 * get execution time in seconds at current point of call in seconds
 * @return float Execution time at this point of call
 */
function get_execution_time()
{
    static
$microtime_start = null;
    if(
$microtime_start === null)
    {
       
$microtime_start = microtime(true);
        return
0.0;
    }   
    return
microtime(true) - $microtime_start;
}
get_execution_time();

?>

However it is true that result depends of gettimeofday() call. ([jamie at bishopston dot net] wrote this & I can confirm)
If system time change, result of this function can be unpredictable (much greater or less than zero).
jamie at bishopston dot net 30-Dec-2010 09:55
All these timing scripts rely on microtime which relies on gettimebyday(2)

This can be inaccurate on servers that run ntp to syncronise the servers
time.

For timing, you should really use clock_gettime(2) with the
CLOCK_MONOTONIC flag set.

This returns REAL WORLD time, not affected by intentional clock drift.

This may seem a bit picky, but I recently saw a server that's clock was an
hour out, and they'd set it to 'drift' to the correct time (clock is speeded
up until it reaches the correct time)

Those sorts of things can make a real impact.

Any solutions, seeing as php doesn't have a hook into clock_gettime?

More info here: http://tinyurl.com/28vxja9

http://blog.habets.pp.se/2010/09/
gettimeofday-should-never-be-used-to-measure-time
Robin Leffmann 24-Dec-2010 09:07
While doing some experiments on using microtime()'s output for an entropy generator I found that its microsecond value was always quantified to the nearest hundreds (i.e. the number ends with 00), which affected the randomness of the entropy generator. This output pattern was consistent on three separate machines, running OpenBSD, Mac OS X and Windows.
 
The solution was to instead use gettimeofday()'s output, as its usec value followed no quantifiable pattern on any of the three test platforms.
gomodo at free dot fr 17-Jun-2009 12:32
Need a mini benchmark ?
Use microtime with this (very smart) benchmark function :

mixed mini_bench_to(array timelist[, return_array=false])
return a mini bench result

-the timelist first key must be 'start'
-default return a resume string, or array if return_array= true :
'total_time' (ms) in first row
details (purcent) in next row

example :
<?php
unset($t);    // if previous used

//-- zone to bench
$t['start'] = microtime(true);
$tab_test=array(1,2,3,4,5,6,7,8);
$fact=1;
$t['init_values'] = microtime(true);
foreach (
$tab_test as $key=>$value)
{
   
$fact=$fact*$value;
}
$t['loop_fact'] = microtime(true);
echo
"fact = ".$fact."\n";
//-- END zone to bench

echo "---- string result----\n";
$str_result_bench=mini_bench_to($t);
echo
$str_result_bench; // string return
echo "---- tab result----\n";
$tab_result_bench=mini_bench_to($t,true);
echo
var_export($tab_result_bench,true);
?>
this example return:

---- string result----
total time : 0.0141 ms
start -> init_values : 51.1 %
init_values -> loop_fact : 48.9 %
---- tab result----
array (
  'total_time' => 0.0141,
  'start -> init_values' => 51.1,
  'init_values -> loop_fact' => 48.9,
)

The function to include :

<?php
function mini_bench_to($arg_t, $arg_ra=false)
  {
   
$tttime=round((end($arg_t)-$arg_t['start'])*1000,4);
    if (
$arg_ra) $ar_aff['total_time']=$tttime;
    else
$aff="total time : ".$tttime."ms\n";
   
$prv_cle='start';
   
$prv_val=$arg_t['start'];

    foreach (
$arg_t as $cle=>$val)
    {
        if(
$cle!='start')   
        {
           
$prcnt_t=round(((round(($val-$prv_val)*1000,4)/$tttime)*100),1);
            if (
$arg_ra) $ar_aff[$prv_cle.' -> '.$cle]=$prcnt_t;
           
$aff.=$prv_cle.' -> '.$cle.' : '.$prcnt_t." %\n";
           
$prv_val=$val;
           
$prv_cle=$cle;
        }
    }
    if (
$arg_ra) return $ar_aff;
    return
$aff;
  }
?>
luke at lucanos dot com 29-May-2008 01: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"
?>
EdorFaus 16-May-2006 09: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
radek at pinkbike com 25-Nov-2005 05:48
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
vladson at pc-labs dot info 19-Jun-2005 12:49
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";
?>