Date/Time 函数
在线手册:中文 英文
PHP手册

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


Date/Time 函数
在线手册:中文 英文
PHP手册
PHP手册 - N: 返回当前 Unix 时间戳和微秒数

用户评论:

langpavel at phpskelet dot org (19-May-2011 09: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).

Harald Hanek (15-Jan-2011 11:10)

As float with more accuracy.

<?php
function getmicrotime($e = 7)
{
    list(
$u, $s) = explode(' ',microtime());
    return
bcadd($u, $s, $e);
}
echo
getmicrotime();
?>

jamie at bishopston dot net (30-Dec-2010 08: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 08: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.

Anonymous (24-Sep-2010 05:53)

that related to the prescedence of the . operator

<?php
# normal prescedence
$a = "te" .   1 - 2   . "st"; # ((te . 1) - 2 ) . st ==> -2st
$b = "te" .   1 + 2   . "st"; # ((te . 1) + 2 ) . st ==>  2st

# modified prescedence
$c = "te" . ( 1 - 2 ) . "st"; # te . ( 1 - 2 ) . st ==> te-1st
$d = "te" . ( 1 + 2 ) . "st"; # te . ( 1 + 2 ) . st ==> te3st

var_dump( $a, $b );
var_dump( $c, $d );

Paul (21-Aug-2010 07:44)

Something I noticed:
If you directly echo the time difference between start and the end you'll get a negative value most of the time. If you calculate first this will work correctly:

<?php
//This will produce in negative value:
$start = microtime();
for(
$i=100;$i>0;$i--){
echo
$i;
}
$end = microtime();

echo
'Took:'.$end-$start.' seconds';
?>

<?php
//This will produce a correct value
$start = microtime();
for(
$i=100;$i>0;$i--){
echo
$i;
}
$end = microtime();
$parseTime = $end-$start;

echo
'Took:'.$parseTime.' seconds';
?>

Andris (10-Aug-2010 10:23)

I wrote a class which allows to time execution of php scripts very easily. You can even time multiple separate blocks and then get the total time at the end.

The class is pretty long so I won't post it here, but here's the link:
http://codeaid.net/php/calculate-script-execution-time-(php-class)

An quick usage example:
<?php
for ($i = 0; $i < 100; $i++) {
    
// calculate the time it takes to run fx()
    
Timer::start();
    
fx();
    
Timer::stop();
 
    
fy();
 
    
// calculate the time it takes to run fz()
    
Timer::start();
    
fz();
    
Timer::stop();
}
 
print
Timer::get();
?>

leonardonobre at ibest dot com dot br (17-Jul-2010 02:20)

Convert date type MySQL to Brazilian (i.e: 2010-07-23 to 23/07/2010);

<?php
$date_brazilian
= date("Y-m-d",microtime($_REQUEST[data_inicial]));
?>

The var $_REQUEST[data_inicial] = 23/07/2010 and convert to microtime (Unix TimeStamp) and the function date convert to format "Y-m-d".

Léo

strata_ranger at hotmail dot com (01-Oct-2009 07:42)

Another version of a stopwatch-style function, this one with the following features:
- Can evaluate any function (callback) with any arbitrary arguments
- Can specify the # of iterations to run

The obvious caveat is of course to take the return value with a grain of salt, especially since this one doesn't run in the tightest loop possible.  A little eval() work could probably fix that, but in the meantime calling this function with no arguments will make it establish a reference point (using pi() ) to measure subsequent calls against -- sort of like hitting the "zero" button on a food scale.

<?php
function stopwatch()
// stopwatch([$limit], [$callback], [$args ... ])
// $limit - # of iterations to run
// $callback - function to time
// $args - arguments for function
//
{
  static
$zero = 0;
  static
$limit = 99999;

 
$args = func_get_args() + Array(null);
 
 
// Check for # iterations, assign for future calls
 
if (is_integer($args[0])) $max = min(array_shift($args), 999999); else $max = $limit;
  if (
$max != $limit)
  {
   
$limit = $max;
   
$zero = 0;
  }
  if (isset(
$args[0])) $callback = array_shift($args); else $callback = null;

  if (
is_null($callback))
  {
   
// Use a very small function as a reference point
   
$callback = 'pi';
   
$zero = null;
  } 

 
// Ensure a valid callback
 
if (!is_callable($callback, false, $name)) return null;
  if (
$name == __FUNCTION__) return null;

 
// The actual loop
 
$st = explode(' ',microtime());
  for(
$cx=0$cx<$max$cx++)
  {
   
call_user_func_array($callback, $args);
  }

 
// Final calculations
 
$t = explode(' ', microtime());
 
$t[0] -= $st[0];
 
$t[1] -= $st[1];
 
  if (
is_array($zero)) // Use previous reference point
 
{
   
$t[0] -= $zero[0];
   
$t[1] -= $zero[1];
  }
  elseif (
is_null($zero)) // or establish a new one
 
{
   
$zero = $t;
    return;
  }
 
  if (
$t[0] < 0) // Ensure microseconds are always positive
 
{
   
$t[0]++; $t[1]--;
  }

 
// Done
 
return "$t[1] + $t[0]s"
}

function
faster()
{
  return;
}

function
slower()
{
  return
fmod(5,2);
}

echo
"<p>Comparing two functions...</p>";
var_dump(stopwatch('faster'));
var_dump(stopwatch('slower'));

echo
"<p>Comparing 100,000 iterations of two functions...";
var_dump(stopwatch(100000, 'faster'));
var_dump(stopwatch('slower'));

echo
"<p>Run a single function 500 times...</p>";
var_dump(stopwatch(500));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));

echo
"<p>Run a single function 555,555 times...</p>";
var_dump(stopwatch(555555));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));

echo
"<p>Fail sanity test...</p>";
var_dump(stopwatch('stopwatch')); // Attempt to time itself!
?>

bleakwind at gmail dot com (16-Sep-2009 06:19)

Check Program runtime:
<?php

class bwruntime
{
    var
$timestart;
    var
$digits;

    function
bwruntime($digits = "")
    {
       
$this->timestart    = explode (' ', microtime());
       
$this->digits       = $digits;
    }

    function
totaltime()
    {
       
$timefinish         = explode (' ', microtime());
        if(
$this->digits == ""){
           
$runtime_float  = $timefinish[0] - $this->timestart[0];
        }else{
           
$runtime_float  = round(($timefinish[0] - $this->timestart[0]), $this->digits);
        }
       
$runtime = ($timefinish[1] - $this->timestart[1]) + $runtime_float;
        return
$runtime;
    }
}
?>

thawootah (03-Aug-2009 12:23)

Want to make sure your script doesn't time out on large updates? Say you're doing a poor mans cron job or working with large amounts of data in loop and the user begins to hang too long. Instead of them giving up and leaving you can break the loop when it reaches a set time and still display data.

Here's a simple handy dandy loop timer rounded to second.
<?php
$starttime
= round(microtime(true));
$totaltime  = 0;
$maxtime = 5; //seconds
for ($i = 1; $i <= 20; $i++) {  /// 20 loops 1 sec each

       
usleep(1000000);

    if(
$totaltime < $maxtime){
   
$currenttime = round(microtime(true));
   
$totaltime = $totaltime + ($currenttime -$starttime);
       
//update and continue
   
echo  $i.'<br>';
   
    }else{
       
// stop updating or display not updated data.
   
break;
    }
}

?>

gomodo at free dot fr (17-Jun-2009 11: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;
  }
?>

singh206 at gmail dot com (10-Apr-2009 07:35)

<?php
class StopWatch {
    public
$total;
    public
$time;
   
    public function
__construct() {
       
$this->total = $this->time = microtime(true);
    }
   
    public function
clock() {
        return -
$this->time + ($this->time = microtime(true));
    }
   
    public function
elapsed() {
        return
microtime(true) - $this->total;
    }
   
    public function
reset() {
       
$this->total=$this->time=microtime(true);
    }
}

$stopwatch = new StopWatch();
usleep(1000000);
echo
"Checkpoint 1: ".$stopwatch->clock()." seconds<br />";

usleep(1000000);
echo
"Checkpoint 2: ".$stopwatch->clock()." seconds<br />";

echo
"Total Elapsed: ".$stopwatch->elapsed()." seconds<br />";
?>

SimonB (07-Nov-2008 11:10)

Here is a simple way to measure the clients connection speed (assuming the server is able to supply fast enough). It measures how much data is transfered in one second and reports the result.

I needed to measure this to offer sensible defaults for selecting live streams at different bitrates for a webcasting application.

<?php
function measure_kbps()
{
 
//Return the unix timestamp + microseconds
 
function micro_time()
  {
   
$timearray = explode(" ", microtime());
    return (
$timearray[1] + $timearray[0]);
  }

 
//Prepare a 1kB chunk to send
 
for ($i=0; $i<1023; $i++) $chunk.='A';
 
$chunk.='\n';
 
//Hide what happens next
 
echo "<!-- ";
 
//Keep sending 1 kB chunks for 1 second
 
flush();
 
$count=0;
 
$starttime = micro_time();
  do
  {
    echo
$chunk;
   
$count++;
   
flush();
   
$endtime = micro_time();
   
$totaltime = $endtime - $starttime;
   
$totaltime = round($totaltime,5);
  } while (
$totaltime < 1);
  echo
" -->\n";
 
//Return how many kb were sent
 
return ($count * 8);
}
$kbps=measure_kbps();
$mbps=$kbps / 1024;
if (
$mbps > 1 ) echo "Your speed is $mbps Mbps.<br />";
  else echo
"Your speed is $kbps Kbps.<br />";
?>

christ dot boris at nospam gmail dot com (13-Sep-2008 08:39)

Hi, I made a function to get the generation page time :

<?php
function gentime() {
    static
$a;
    if(
$a == 0) $a = microtime(true);
    else return (string)(
microtime(true)-$a);
}
?>

(You can add a round() to the return value if you want)

Use :

<?php
# you should include your libraries/conf files here (including the gentime function)
gentime();

# your source code here

echo 'Generated in '.gentime().' seconds.'
?>

pascalxusPLEASENOSPAM at yahoo dot com (12-Jul-2008 09:19)

I wanted to find out whether echo would be quicker in small chunks or one large chunk to test the theory mentioned in the previous post.  The following experiment shows that there is no significant performance difference, in terms of execution time elapsed, between the two methods of using echo.  I ran two test cases, one with a string that is 100000 bytes long and another with a string length of 1000000.  The source code follows below.

<?php

function echobig($string, $bufferSize = 8192)
{
   
$splitString = str_split($string, $bufferSize);

    foreach(
$splitString as $chunk)
        echo
$chunk;
}

global
$dat;
$dat = "";

function
testit()
{
global
$dat;
$data = "";

for(
$a = 0; $a <= 1000000; $a += 1 ) $data .= "a";

$u1= microtime(true);
echobig( $data );
$u2= microtime(true);
echo
$data;
$u3= microtime(true);

$diff = $u2 - $u1;
$diff2= $u3 - $u2;
$dat .= "$diff2 $diff    $u2  $u1\r\n";
}

$i = 0;
while(
$i < 5 )
{
 
testit(); $i += 1;
}

global
$dat;
$fp = fopen( "../Data/results.txt", "w" );
fwrite( $fp, $dat );
fclose( $fp );
?>

You can run the above experiment yourself or you can look at my test data.  I got some test data here:  http://www.codesplunk.com/examples/echo.html

kpsimoulis [at] genatec (05-Jun-2008 08: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

Peter Kehl (30-May-2008 11: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 12: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"
?>

admin at emuxperts dot net (21-Aug-2006 03: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
?>

EdorFaus (16-May-2006 08: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 04: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 11: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";
?>

php at washboardabs dot net (24-Feb-2005 08:57)

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.

mcq at supergamez dot hu (12-Dec-2000 06:47)

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