microtime

(PHP 4, PHP 5, PHP 7)

microtimeGibt den aktuellen Unix-Timestamp/Zeitstempel mit Mikrosekunden zurück

Beschreibung

mixed microtime ([ bool $get_as_float = false ] )

microtime() gibt den aktuellen Unix-Timestamp mit Mikrosekunden zurück. Diese Funktion steht nur auf Systemen zur Verfügung, die den Systemaufruf gettimeofday() unterstützen.

Parameter-Liste

get_as_float

Wenn auf TRUE gesetzt, gibt microtime() einen float anstatt einem string zurück, wie in der Rückgabewert-Sektion unten genauer erläutert wird.

Rückgabewerte

Standardmäßig gibt microtime() einen string im Format "Mikrosekunden Sekunden" zurück, wobei Sekunden die Sekunden seit Beginn der Unix Epoche (01. Januar 1970 00:00:00 GMT) sind und Mikrosekunden die Anzahl an Mikrosekunden misst, die seit Sekunden vergangen sind, was ebenso in Sekunden ausgedrückt wird.

Wenn get_as_float TRUE ist, gibt microtime() stattdessen einen float zurück, welcher die aktuelle Zeit in Sekunden seit Beginn der Unix Epoche angibt (die Nachkommastellen geben die Mikrosekunden an).

Beispiele

Beispiel #1 Zeitmessung einer Skriptausführung mit microtime()

<?php
/**
 * Einfache Funktion zum Replizieren des PHP 5-Verhaltens
 */
function microtime_float()
{
    list(
$usec$sec) = explode(" "microtime());
    return ((float)
$usec + (float)$sec);
}

$time_start microtime_float();

// Die Skriptverarbeitung fuer einen bestimmten Zeitraum unterbrechen
usleep(100);

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

echo 
"In $time Sekunden nichts getan\n";
?>

Beispiel #2 Zeitmessung einer Skriptausführung in PHP 5

<?php
$time_start 
microtime(true);

// Die Skriptverarbeitung fuer einen bestimmten Zeitraum unterbrechen
usleep(100);

$time_end microtime(true);
$time $time_end $time_start;

echo 
"In $time Sekunden nichts getan\n";
?>

Beispiel #3 microtime() und REQUEST_TIME_FLOAT (ab PHP 5.4.0)

<?php
// zufällige Pausendauer
usleep(mt_rand(10010000));

// Ab PHP 5.4.0 ist REQUEST_TIME_FLOAT im superglobale $_SERVER Array verfügbar.
// Es enthält den Zeitstempel des Beginns des Request in Mikrosekunden-Auflösung.
$time microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

echo 
"Nichts getan in $time Sekunden\n";
?>

Siehe auch

  • time() - Gibt den aktuellen Unix-Timestamp/Zeitstempel zurück

add a note add a note

User Contributed Notes 15 notes

up
132
player27
4 years ago
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;
?>
up
53
Russell G.
4 years ago
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.
up
38
jamie at bishopston dot net
6 years ago
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
up
20
radek at pinkbike com
12 years ago
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
up
11
gomodo at free dot fr
8 years ago
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;
  }
?>
up
7
luke at lucanos dot com
9 years ago
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"
?>
up
3
EdorFaus
11 years ago
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
up
4
Robin Leffmann
6 years ago
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.
up
1
Daniel Rhodes
4 years ago
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
up
1
Nads
4 years ago
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.
up
0
johovich at yandex dot ru
1 month ago
//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];
}
up
0
how to set nonce value with microtime
3 months ago
Using microtime() to set 'nonce' value:

ini_set("precision", 16);
$nonce="nonce=".microtime(true)/0.000001;
up
0
thomas
5 years ago
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
}
up
-1
langpavel at phpskelet dot org
6 years ago
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).
up
-1
vladson at pc-labs dot info
12 years ago
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";
?>
To Top