microtime

(PHP 3, 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() 将返回一个浮点数。

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

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


add a note add a note User Contributed Notes
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();
var_dump($t->fetch()); // Outputs: float(0)

// ------------------------------------------------------

?>
EdorFaus
17-May-2006 03: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
no dot spam at in dot my dot mail
16-May-2006 04:49
In reply to "me at whereever dot com" below, this is what SQL transactions are for. There's is absolutely no reason to use the microtime as a DB index, unless it holds some intrinsic meaning to do so, ie. only when it makes sense to have the microtime as your (primary) key.
Eric Pecoraro
01-May-2006 11:35
Even though this function uses gettimeofday(), it fits better here. I created it to provide unique IDs for image names that were being process in a fast loop scenario.

<?php
// 15 Digit Microtime Stamp (returns a 15 digit timestamp/unique id inside loops)
// Inspired by Christian Wenz's excellent "PHP Phrasebook".
function microtimestamp($id='') {
  
$stamp = gettimeofday();
  
// id insures unique id in fast loops, no id is in sync w/ PHP's time() function
  
if ($id=='id') { $divby=100000; } else { $divby=1000000; }
  
$stamp = $stamp['sec'] + $stamp['usec'] / $divby ;
  
$stamp = str_replace('.','',$stamp);
  
$stamp = substr($stamp.'00000',0,15) ; // for consistent length
  
return $stamp
}
// TESTS
// synced with time() function
echo '<b>'.time()." <- time()</b><br>\n";
while (
$cnt < 11 ) {
  
$cnt++;
   echo
microtimestamp() . "<br>\n";
}
// adds a few random seconds to time() ... but produces unique ids in fast loop
echo "<b>Unique IDs</b><br>\n";
while (
$cnt2 < 11 ) {
  
$cnt2++;
   echo
microtimestamp('id') . "<br>\n";
}
?>
floppie at quadra-techservices dot com
17-Apr-2006 09:14
It's pretty easy to know the value before you insert the new row.  You can either select the last row with:

<?php
  
// replace `id` with whatever you named your auto_increment field
  
$query = 'SELECT `id` FROM `table_in_question` ORDER BY `id` DESC LIMIT 0, 1';
   if(!
$sql = mysql_query($query)) {
       die(
'Query failed near ' . __FILE__ . ':' . __LINE__);
   }
   list(
$id) = mysql_fetch_row($sql);
  
$next_id = $id + 1;
?>

And assume there are no breaks in the table.  If your application can safely ensure this, this is the simplest way to do it.  Or, if your application cannot ensure this, you can use this:

<?php
   $query
= 'SHOW TABLE STATUS LIKE \'table_in_question\'';
   if(!
$sql = mysql_query($query)) {
       die(
'Query failed near ' . __FILE__ . ':' . __LINE__);
   }
  
$row = mysql_fetch_row($sql);
  
$next_autoincrement = $row[10];
  
/* ----------------- OR --------------------- */
  
$row = mysql_fetch_array($sql);
  
$next_autoincrement = $row['Auto_increment'];
?>

Both work quite well.  I use the first in my game for certain insertions.
me at whereever dot com
30-Mar-2006 05:34
Just to say that what "junk" said about using the timestamp for indexes does make sense in some situations.  For instance, I have a deliverables management page that does 2 things:
1) FTP transfer of the file to the server.  This operation requires the file to be transfered to a directory specific to that one delivery
2) Create an entry in database with all the details of the delivery, including the filepath for download purposes.

If I wanted to use the auto increment function, there would be no way for me to know the index of the DB entry before actually doing the insert.  So to work consistently I would have to do:

DB insert -> Fetch the index value -> Try to upload the file -> if transfer fails: delete DB entry

With timestamp it would look like this:
Compute timestamp -> Try file transfer -> DB insert if transfer OK

The choice is yours I guess
webmaster [AT] dtronix [DOT] com
22-Mar-2006 07:01
Here is a small script I made so that I would not have to deal with vars.  All you have to do is run the function twice and the second time run, it will echo the runtime.  If you place a number in the last function "script_runtime(5)" it will round off the number to that decimal place.

<?php
function script_runtime ( $round = 20 ) {
        
//Check to see if the global is already set
        
if ( !empty( $GLOBALS['start_script_runtime'] ) ) {
                  
//The global was set. So, get the current microtime and explode it into an array.
                  
list($msec, $sec) = explode(" ", microtime());
                   echo
round(($sec + $msec) - $GLOBALS['start_script_runtime'], $round);
         } else {
                  
// The global was not set. Create it!
                  
list($msec, $sec) = explode(" ", microtime());
                  
$GLOBALS['start_script_runtime'] = $sec + $msec;
         }
}

// Example:

script_runtime();

sleep(1);

script_runtime();

?>
jj
09-Mar-2006 06:53
A 14 digit unique timestamp

function uniqueTimeStamp() {
  $milliseconds = microtime();
  $timestring = explode(" ", $milliseconds);
  $sg = $timestring[1];
  $mlsg = substr($timestring[0], 2, 4);
  $timestamp = $sg.$mlsg;
  return $timestamp;
}

echo uniqueTimeStamp();
alien999999999 at users dot sourceforge dot net
22-Feb-2006 03:48
so true, use mysql auto_increment!

but for those, who wish to output logs with those totally stupid timestamps (like qmail) (instead of nicely readable normal timestrings), use this for the really shortest way:

function stupid_timestamp()
{
   list($msec,$sec)=split(' ',microtime);
   return $sec.'.'.$msec;
}
17-Feb-2006 12:07
i hope everyone who reads junk at plaino dot com's comment realizes how stupid that is. sql has a built-in auto-increment-function for indexes which I'm sure is much more optimized, easier to understand and lastly it makes more sense than using a number like that =/
Z0d
13-Feb-2006 11:03
The shortest way for PHP4 users really is

$ts = strtok(microtime(), ' ') + strtok('');
d dot schneider at 24you dot de
12-Feb-2006 06:30
Here the short way.

<?
$floattime
= array_sum(explode(chr(32), microtime()));
?>
adiwicaksono at yahoo dot com
03-Feb-2006 11:19
<?
function uniqueTimeStamp(){
  
$Asec  = explode(" ", microtime());
  
$Amicro = explode(".", $Asec[0]);
   return (
$Asec[1].substr($Amicro[1], 0, 4));
}

for(
$i = 0; $i < 10000; $i++){
       print (
uniqueTimeStamp());
       print
"\n";
}
?>

uniqueTimeStamp() is not Unique :)

Try this instread

$idmessage  = substr(substr(uniqid(mktime(),4),16),0,8);

Unique
junk at plaino dot com
10-Jan-2006 07:35
Here's a quick function to output a unique number. Good for MySQL / SQL idexes and unique id values.

function uniqueTimeStamp_float(){
   $Asec = explode(" ", microtime());
   $Amicro = explode(".", $Asec[0]);
   return ($Asec[1].".".substr($Amicro[1], 0, 4));
}

print (uniqueTimeStamp_float());

// outputs a unique something like:
// 1136849268.0180

function uniqueTimeStamp(){
   $Asec = explode(" ", microtime());
   $Amicro = explode(".", $Asec[0]);
   return ($Asec[1].substr($Amicro[1], 0, 4));
}

print (uniqueTimeStamp());

// outputs a unique something like:
// 11368492680180
ed [at] twixcoding [dot] com
08-Jan-2006 08:57
I personally use the following class, created by myself, to record page creation time.
<?php
class Timer {
// Starts, Ends and Displays Page Creation Time
  
function getmicrotime() {
       list(
$usec, $sec) = explode(" ", microtime());
       return ((float)
$usec + (float)$sec);
   }   
  
   function
starttime() {
  
$this->st = $this->getmicrotime();
   }
      
   function
displaytime() {
      
$this->et = $this->getmicrotime();
       return
round(($this->et - $this->st), 3);
   }
}
?>

Called by doing the following

<?php

$time
= new Timer;
$time->starttime();

// The rest of your script

echo 'Script took '.$time->displaytime().' seconds to execute'

?>
saphir at trinity-lab dot com
30-Nov-2005 01:37
A simple class in PHP5 allowing to know the execution time of a script :

<?php
class Timer
{
  
private $m_Start;

  
public function __construct()
   {
      
$this->m_Start = 0.0;
   }

  
private function GetMicrotime()
   {
       list(
$micro_seconds, $seconds) = explode(" ", microtime());
       return ((float)
$micro_seconds + (float)$seconds);
   }

  
public function Init()
   {
      
$this->m_Start = $this->GetMicrotime();
   }

  
public function GetTime($Decimals = 2)
   {
       return
number_format($this->GetMicrotime() - $this->m_Start, $Decimals, '.', '');
   }
}

$MyTimer = new Timer();
$MyTimer->Init();

sleep(1);

echo
$MyTimer->GetTime();

// Output result -> 1.00
?>

Nico.
radek at pinkbike com
25-Nov-2005 12: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
logix dot Spam-me-not at hacker dot dk
14-Nov-2005 11:18
Regarding discussion about generation of passwords using microtime.
Its proberbly "ok" for a first-time password, but it is NOT better than random.

Cryptographicly there will very limited keyspace to test of you use this method.

If the stored password hash was to fall into wrong hands it would quite easily be cracked, as there are several factors that limits the combinations. Especially if you know ca. what time the password was issued.

The string output from microtime looks like this:
 - 0.93839800 1131978543

The first number is always 0.
On my computer, it seems that the 7th and 8th number are always "00", so lets assume that as well.
In the last number (the epoch timestamp), there are only 3.600 combinations (=seconds) in an hour.

That leaves 6 unpredictable digits (the 938398 above).
thats 10^6 = 1.000.000 (combinations).

1.000.000 combinations can be checked in 55 seconds on my 3.2ghz
So the time it takes to crack is 55 seconds, times the number of seconds youre guessing (in the timestamp)..

If, say, you know ca. when the password was created, +-5minutes. That a 10 minute total, a span of 600 combinations, that would be:
600(seconds) * 55 (seconds crack time) = 9 hours.

And that using just 1 computer..
philip dot waters dot pryce at gmail dot com
12-Nov-2005 11:53
Surely This Would Be Easyer  Chris (21-Jan-2005 03:17)
Quote:
Want to generate a unique default password for a user?

$password = md5(microtime());

That is much better than using a random number!
-----
$password = md5(rand(0,microtime()));
That Would Most Definate Be Much More Random :D And Harder To Break
sybeer dot SuperSpamKiller at wp dot pl
05-Nov-2005 07:25
I write two line script generation time code (inspirated by samples above):

<?php
$startTime
= array_sum(explode(" ",microtime()));

<<
some php code>>

echo
round((array_sum(explode(" ",microtime())) - $startTime),4).' sec';

// number four tell how many digits will be print

?>

example code execution reslults
0.4983 sec

<>
martijn at vanderlee dot com
28-Sep-2005 02:55
For highly accurate performance timing of an algorithm, you'll need to take into account the time it takes to run microtime() and/or a replacement function such as the microtime_float.
Make sure to keep all calculations outside the timers.

Here's a small sample. Please note that it takes into account the assignment of one variable as well during calibration, since this will happen in the actual test as well.

$calibrate_begin = microtime_float();
$calibrate_end = microtime_float();
$overhead_time = $calibrate_end - $calibrate_begin;

$performance_begin = microtime_float();

// test

$performance_end = microtime_float();

$result_time = ($performance_end - $performance_begin) - $overhead_time;

For even more accuracy in testing, loop the ENTIRE code a number of times. If you just loop the calibration and test independantly, you'll get misleading results due to time spent running the loop codes themselves.
17-Aug-2005 06:06
<?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();

//*****
//***** Use round with 4 spaces after the decimal for shorter times. The output would be 0.003 seconds
//*****
$time = round($time_end - $time_start, 4);

echo
"Did nothing in $time seconds\n";
?>
DEBO Jurgen <jurgen AT person DOT be>
21-Jul-2005 12:48
To generate parsing time of a HTML page:
This works with a STATIC var. So You do
not need to store starttime at all.

Usage : Call this twice on top of Your template,
       and before </body>

function stopwatch(){
   static $mt_previous = 0;

   list($usec, $sec) = explode(" ",microtime());
   $mt_current = (float)$usec + (float)$sec;

   if (!$mt_previous) {
     $mt_previous = $mt_current;
     return "";
   } else {
     $mt_diff = ($mt_current - $mt_previous);
     $mt_previous = $mt_current;
     return sprintf('%.16f',$mt_diff);
   }
}
vladson at pc-labs dot info
19-Jun-2005 06: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";
?>
rsalazar at innox dot com dot mx
18-Jun-2005 06:20
Yet another way to achieve the same effect without the loss of decimals is with the PCRE replace function (preg_replace), which also seems to be a _bit_ faster (about 2.5E-05 sec):

<?php
   $float_time
= preg_replace('/^0?(\S+) (\S+)$/X', '$2$1', microtime());
 
?>

PS unluckypixie, "james at gogo dot co dot nz" wrote the same at Dec/2004
unluckypixie
18-May-2005 05:53
I don't know why no-one else has suggested this, but clearly the easiest way to replicate the PHP5 behaviour is to do:

$mtime = array_sum(explode(" ",microtime()));

I challenge anyone to write it shorter and neater than that ;o)
t0russ at gmail dot com
03-May-2005 09:24
<?php
/*
compares runtimes of 2 functions
to use, copy/paste functions, and call them from fct1 and fct2

coded by t0rus
*/
function stripQuotes1($st){
   while((
$k=strpos($st,'"'))!==false)
      
$st=substr($st,0,$k).substr($st,$k+1);
   while((
$k=strpos($st,'\''))!==false)
      
$st=substr($st,0,$k).substr($st,$k+1);
   return
$st;
}
function
stripQuotes2($str){
   for(
$i=0;$i<strlen($str);$i++)
   if ((
$str{$i}==="'")||($str{$i}==='"')){ // === gave better results than ==
      
$str=substr($str,0,$i).substr($str,$i+1);
      
$i--;
   }
   return
$str;
}

$runtimes=1000;//how many times to run the tests
function fct1(){
  
stripQuotes1('01abba6"78901\' 1234""12345678\"123-"""3\'\'2');
}
function
fct2(){
  
stripQuotes2('01abba6"78901\' 1234""12345678\"123-"""3\'\'2');
}

//################################################################//
$time1=0;
for (
$i=0;$i<$runtimes;$i++){
  
$time_start = array_sum(explode(' ', microtime()));
  
fct1();
  
$time_end = array_sum(explode(' ', microtime()));
  
$time1 = ($time1*$i+$time_end - $time_start)/($i+1);
}
echo
"\nfct1 runs in $time1 ms.\n";
$time2=0;
for (
$i=0;$i<$runtimes;$i++){
  
$time_start = array_sum(explode(' ', microtime()));
  
fct2();
  
$time_end = array_sum(explode(' ', microtime()));
  
$time2 = ($time2*$i+$time_end - $time_start)/($i+1);
}
echo
"\nfct2 runs in $time2 ms.\n";
$tf = round($time2/$time1);
echo
"\nfct".(($tf>1)?'1 is faster by a factor of '.$tf:(($tf<1)?'2 is faster by a factor of '.round($time1/$time2):'1 is roughly equal to fct2'))."\n\n";
?>
Sample output:

fct1 runs in 0.00017227101325989 ms.

fct2 runs in 0.0010822315216064 ms.

fct1 is faster by a factor of 6
d dot triendl at aon dot at
10-Apr-2005 06:55
james at gogo dot co dot nz made a small mistake:

Here's the fixed one:
<?php
$floattime
= (float) array_sum(explode(' ', microtime());
//or shorter
$floattime = array_sum(explode(' ', microtime()));
?>
09-Apr-2005 12:07
I like more this way of presenting the microtime:
<?php

function utime(){
  
$time = microtime();
   return
substr($time, 11, 10).substr($time, 1, 7);
}

print
utime(); // 1112975697.842941

?>
Sweet short string :)
admin at createblog dot com
05-Apr-2005 11:59
The code provided by joelatlearnossdotcom is incorrect. That will only produce the microseconds of the current time. Here's what it should look like:

<?
$time
= microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$start = $time;

// --------------
// your code here
// --------------

$time = microtime();
$time = explode(' ', $time);
$time = $time[1] + $time[0];
$finish = $time;
$total_time = round(($finish - $start), 6);
?>

with $total_time being the script execution time.
edwardzyang at thewritingpot dot com
15-Mar-2005 10:31
Here is a modified version of the chronometer functions. It acts like a "lap watch", immediately starting another timing session right after you call it. It also lets you specify the return value to be in seconds or in milliseconds: this is useful when a microsecond() timing would return a negative value.

<?php
/*
 * Slightly modified from http://www.php.net/manual/en/function.microtime.php, adds
 * support for Second values (as microtime can cause problems when you run extended loops).
 * It also is "unstopped" timing, that is, the timer never sleeps.
*/
$CHRONO_STARTTIME = 0;
define("RET_TIME", "ms"); //Can be set to "ms" for milliseconds
or "s" for seconds
function chronometer()
{
   global
$CHRONO_STARTTIME;
  
  
$now = microtime(TRUE);  // float, in _seconds_
  
  
if (RET_TIME === 's') {
      
$now = $now + time();
      
$malt = 1;
      
$round = 7;
   } elseif (
RET_TIME === 'ms') {
      
$malt = 1000;
      
$round = 3;
   } else {
       die(
"Unsupported RET_TIME value");
   }
  
   if (
$CHRONO_STARTTIME > 0) {
      
/* Stop the chronometer : return the amount of time since it was started,
       in ms with a precision of 3 decimal places, and reset the start time.
       We could factor the multiplication by 1000 (which converts seconds
       into milliseconds) to save memory, but considering that floats can
       reach e+308 but only carry 14 decimals, this is certainly more precise */
      
      
$retElapsed = round($now * $malt - $CHRONO_STARTTIME * $malt, $round);
      
      
$CHRONO_STARTTIME = $now;
      
       return
$retElapsed;
   } else {
      
// Start the chronometer : save the starting time
    
      
$CHRONO_STARTTIME = $now;
      
       return
0;
   }
}
?>

It can be used like this:

<?php

chronometer
();
//Do stuff;
echo chronometer(); //this will return the time taken to "Do stuff"
//Do more stuff
echo chronometer(); //this will return the time taken to "Do more stuff"

?>
joelatlearnossdotcom
13-Mar-2005 12:31
A simpler page execution script would be the following:

<?php

echo ("Page executed in ");
$execute = microtime();
print (
number_format($execute,4));
echo (
" seconds.");

?>

// prints out following:

Page executed in 0.5364 seconds.
php at washboardabs dot net
24-Feb-2005 04: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.
David Genord II
24-Feb-2005 12:13
Here is a little more versitile version of the chronometer script below.

/************************************************************
*
*    void | float chronometer($timer)
*
*    Works exactly like a stop watch, ie. starts if stopped
*    and stops if started
*
*    Call the function a first time to start the chronometer.
*    The next call to the function will return the number of
*    milliseconds elapsed since the chronometer was started
*    (rounded to three decimal places). The next call
*    will start the chronometer again from where it finished.
*
*    Multiple timers can be used by creating multiple $timer
*    variables.
*
*    An example script would be:
*   
*    chronometer($timer1);
*    DO STUFF HERE
*    chronometer($timer2);
*    chronometer($timer3);
*    DO MORE STUFF
*    echo chronometer($timer1);
*    DO SOMETHING
*    echo chronometer($timer3);
*    DO SOMETHING
*    echo chronometer($timer2);
*
*    The timer variables do not need to be declared or
*    initialized before use
*
************************************************************/

function chronometer(&$CHRONO_STARTTIME)
{
   $now = microtime(TRUE);  // float, in _seconds_
  
   if(isset($CHRONO_STARTTIME['running']))
   {
       if($CHRONO_STARTTIME['running'])
       {
           /* Stop the chronometer : return the amount of time since it was started,
           in ms with a precision of 3 decimal places.
           We could factor the multiplication by 1000 (which converts seconds
           into milliseconds) to save memory, but considering that floats can
           reach e+308 but only carry 14 decimals, this is certainly more precise */
          
           $CHRONO_STARTTIME['elapsed'] += round($now - $CHRONO_STARTTIME['temp'], 3);
           $CHRONO_STARTTIME['running'] = false;

          
           return $CHRONO_STARTTIME['elapsed'];
       }
       else
       {
           $CHRONO_STARTTIME['running'] = true;
           $CHRONO_STARTTIME['temp'] = $now;
       }
   }
   else
   {
       // Start the chronometer : save the starting time
      
       $CHRONO_STARTTIME = array();
       $CHRONO_STARTTIME['running'] = true;
       $CHRONO_STARTTIME['elapsed'] = 0;
       $CHRONO_STARTTIME['temp'] = $now;
   }
}
yonman at nsa dot co dot il
22-Feb-2005 06:50
md5 time stamps can be further hardened by appending a "secret predefined key" (i.e, one that is stored in a hardened position ... a sort of poor man's bi-directional encryption key) after the timestamp, before passed into the md5 function.

a 40-characters long key can seriously hinder the brute force attack described above. Wouldn't use this method for anything really important though ... unless backed up by more layers for defense.
knetknight
04-Feb-2005 11:23
md5(microtime()) is probably a fine method for low security or temporary passwords but I wouldn't use it for anything critical because the pattern is absolutely predictable. e.g. If I have an idea of the time frame in which the password was generated in this manner it'd be a simple matter to write a script that generates all possible md5sums for microtime() within' that frame. The less sure I am of when the password was generated the bigger my list would have to be but you get the idea.
Chris
21-Jan-2005 11:17
Want to generate a unique default password for a user?

$password = md5(microtime());

That is much better than using a random number!
exaton at NOSPAM dot free dot fr
14-Jan-2005 11:50
Here's what I use to time my scripts.

There's a bit of surrounding code in the function, which will induce errors in short cycles ; this should therefore be used in repetitive context where the error will be amortized (cf. also mcq at supergamez dot hu 's comment below).

Note however that the important thing, $now = microtime(TRUE), happens at the very beginning, not suffering from any extraneous delay, and following it at the chronometer start is only one little condition, and a particularly compiler-friendly one at that (I think).

Hope this does not turn out too ugly after wordwrap()...

/************************************************************
*
*    void | float chronometer()
*
*    Enables determination of an amount of time between two points in a script,
*    in milliseconds.
*
*    Call the function a first time (as void) to start the chronometer. The next
*    call to the function will return the number of milliseconds elapsed since
*    the chronometer was started (rounded to three decimal places).
*
*    The chronometer is then available for being started again.
*
************************************************************/

$CHRONO_STARTTIME = 0;

function chronometer()
{
   global $CHRONO_STARTTIME;
                          
   $now = microtime(TRUE);  // float, in _seconds_
  
   if ($CHRONO_STARTTIME > 0)
   {
       /* Stop the chronometer : return the amount of time since it was started,
       in ms with a precision of 3 decimal places, and reset the start time.
       We could factor the multiplication by 1000 (which converts seconds
       into milliseconds) to save memory, but considering that floats can
       reach e+308 but only carry 14 decimals, this is certainly more precise */
      
       $retElapsed = round($now * 1000 - $CHRONO_STARTTIME * 1000, 3);
      
       $CHRONO_STARTTIME = 0;
      
       return $retElapsed;
   }
   else
   {
       // Start the chronometer : save the starting time
      
       $CHRONO_STARTTIME = $now;
   }
}
e dot nijssen at gmail dot com
27-Dec-2004 05:51
here is a handy script generation time code example(scrabble):
<?php
#put this in the very beginning
$timestart = microtime();

<<
some code>>

#put this in the very end
$timeend = microtime();
$diff = number_format(((substr($timeend,0,9)) + (substr($timeend,-10)) - (substr($timestart,0,9)) - (substr($timestart,-10))),4);
echo
"<br><br><small><small>script generation took $diff s </small></small>";
?>

this code will give you the time the <<some code>> took to evaluate in 4 decimals, if you want more or less decimals, edit the last parameter in the line that defines $diff.
james at gogo dot co dot nz
06-Dec-2004 10:17
The docs above show a pretty verbose function for emulating the float functionality available in PHP 5.  Here's a one liner that does the same job without the overhead of the function call.

$floattime = (float) array_sum(explode(' ', microtime());
29-Sep-2004 02:45
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
mcq at supergamez dot hu
12-Dec-2000 02: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