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

search for in the

mktime> <localtime
Last updated: Fri, 14 Nov 2008

view this page in

microtime

(PHP 4, PHP 5)

microtime 現在の Unix タイムスタンプをマイクロ秒まで返す

説明

mixed microtime ([ bool $get_as_float ] )

microtime() は、現在の Unix タイムスタンプをマイクロ秒単位で返します。 この関数は、gettimeofday() システムコールをサポートする オペレーティングシステムでのみ使用できます。

パラメータ

get_as_float

オプション引数を付けずにコールされた場合、この関数は文字列 "msec sec" を返します。ただし、sec は Unix エポック (1970 年 1 月 1 日 0:00:00 GMT) から計算した秒数、msec はマイクロ秒の部分です。 文字列のそれぞれの部分は秒単位で返されます。

get_as_floatTRUE に設定すると、結果を float (秒単位) で返します。

変更履歴

バージョン 説明
5.0.0 get_as_float パラメータが追加されました。

例1 microtime() でタイマスクリプト実行

<?php
/**
 * PHP 5の動作を模擬する簡単な関数
 */
function microtime_float()
{
    list(
$usec$sec) = explode(" "microtime());
    return ((float)
$usec + (float)$sec);
}

$time_start microtime_float();

// しばらくスリープ
usleep(100);

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

echo 
"Did nothing in $time seconds\n";
?>

例2 PHP 5 におけるタイマスクリプト実行

<?php
$time_start 
microtime(true);

// しばらくスリープ
usleep(100);

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

echo 
"Did nothing in $time seconds\n";
?>

参考



mktime> <localtime
Last updated: Fri, 14 Nov 2008
 
add a note add a note User Contributed Notes
microtime
php [spat] hm2k dot org
18-Nov-2008 01:47
1 millisecond = 1000 microseconds

<?php

$millitime
=microtime(1)*1000;

echo
$millitime; //eg: 1227011490530

?>

You should end up with a 13 digit int.
SimonB
07-Nov-2008 12: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 09: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 10: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 09: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 12: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 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"
?>
admin at emuxperts dot net
21-Aug-2006 04: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 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
Z0d
13-Feb-2006 04:03
The shortest way for PHP4 users really is

$ts = strtok(microtime(), ' ') + strtok('');
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";
?>
php at washboardabs dot net
24-Feb-2005 09: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 07: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

mktime> <localtime
Last updated: Fri, 14 Nov 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites