PHP: microtime - Manual

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

search for in the

mktime localtime

Last updated: Sat, 27 Jan 2007

view this page in

# microtime

(PHP 3, PHP 4, PHP 5)

microtime -- Возвращает метку времени с микросекундами

## Описание

mixed microtime ( [bool get_as_float] )

Функция microtime() возвращает текущую метку времени с микросекундами. Эта функция доступна только на операционных системах, в которых есть системная функция gettimeofday().

При вызове без необязательного параметра, возвращается строка в формате "msec sec", где sec - это количество секунд, прошедших с начала Эпохи Unix (The Unix Epoch, 1 января 1970, 00:00:00 GMT), а msec - это дробная часть.

Если передан аргумент `get_as_float`, равный `TRUE`, функция microtime() возвращает действительное число.

> Замечание: Аргумент `get_as_float` появился в `PHP 5.0.0`.

Пример 1. Пример использования функции microtime()

`<?php
function getmicrotime()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = getmicrotime();
for ($i=0; $i < 1000; $i++) {
// Ничего не делать. Повторить 1000 раз
}
$time_end = getmicrotime();
$time = $time_end - $time_start;
echo "Ничего не делал $time секунд\n";
// в PHP 5 то же самое можно сделать вот так:
$time_start = microtime(1);
for ($i=0; $i < 1000; $i++) {
// Ничего не делать. Повторить 1000 раз
}
$time_end = microtime(1);
$time = $time_end - $time_start;
echo "Ничего не делал $time секунд\n";
?>`

См. также описание функции time().

add a note User Contributed Notes
microtime
doom_quake at hotmail dot com
14-Jan-2007 07:51
`heavyraptor,
Optimization should consider two things:
1. The order in which the functions are called (due to load time, and processor prefetch)
2. The number of tests involved (10 is not enough)
I would try the test with 10,000 iterations and once with function 1 called first and once with function 2 called first.
If possible, try not to store results in an array (since this step will get slower as time passes), but rather process them inline. This can be done by storing the min and max time difference between the two functions then comparing and overwriting if the current value is smaller/larger.
Also consider an average difference by adding the current time difference each time then dividing by the number of iterations. This will give you a more accurate picture of the true speed benefit.`
yhoko at yhoko dot com
19-Dec-2006 09:31
`@heavyraptor
Try this one, too:
<?php
function microtime_float()
{
$time = microtime();
return (double)substr( $time, 11 ) + (double)substr( $time, 0, 8 );
}
?>
Yhoko`
heavyraptor
08-Dec-2006 08:53
`By the way, I forgot to post my microtime_float() test results.
Here's my script:
<?php
error_reporting(E_ALL);
header('Content-type: text/plain');
function microtime_float1() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
function microtime_float2() {
return array_sum(explode(' ',microtime()));
}
// Init
for ($i = 0; $i < 10; $i++)
microtime();
$ms1 = array();
$me1 = array();
$ms2 = array();
$me2 = array();
for ($i = 0; $i < 10000; $i++) {
// microtime_float1()
$ms1[] = microtime();
microtime_float1();
$me1[] = microtime();
for ($j = 0; $j < 4; $j++)
microtime();
// microtime_float2()
$ms2[] = microtime();
microtime_float2();
$me2[] = microtime();
}
// Parse time
foreach ($ms1 as $k => $time) $ms1[$k] = array_sum(explode(' ',$time));
foreach ($me1 as $k => $time) $me1[$k] = array_sum(explode(' ',$time));
foreach ($ms2 as $k => $time) $ms2[$k] = array_sum(explode(' ',$time));
foreach ($me2 as $k => $time) $me2[$k] = array_sum(explode(' ',$time));
// Calculate average
$ms1 = array_sum($ms1) / count($ms1);
$me1 = array_sum($me1) / count($me1);
$ms2 = array_sum($ms2) / count($ms2);
$me2 = array_sum($me2) / count($me2);
echo 'microtime_float1() ' . number_format($me1 - $ms1,10) . "\n";
echo 'microtime_float2() ' . number_format($me2 - $ms2,10);
?>
This script calculates the used time by microtime_float1() and microtime_float2().
I get the following results as the biggest differences:
microtime_float1() 0.0000882149
microtime_float2() 0.0000278950
... and these as lowest differences:
microtime_float1() 0.0000467300
microtime_float2() 0.0000417233
of course this may change everytime you reexecute the script. The differences are very little, but this may be important in some scripts.
Result:
As you see, my microtime_float() function is better :D
Anyway, this is all kind of nonsense, because most of the people use PHP 5 and there we just use microtime(true), which gives us the same result as my microtime_float().
So if you're using PHP < 5, use this function below:
<?php
function microtime_float() {
return array_sum(explode(' ',microtime()));
}
?>
Thank you for your attention, have fun :).
... and sorry because of my bad english.`
heavyraptor
06-Dec-2006 10:15
`Instead of using the complicated function below
<?php
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>
you may use my the fast & sexy function
<?php
function microtime_float() {
return array_sum(explode(' ',microtime()));
}
?>
Returns the exactly same result.
have fun :)`
lacent at gmail dot com
15-Nov-2006 06:19
`i've made several timer functions, and different methods of how to check time, for loading and benchmarking and such. this class works pretty good for whatever you might need it for. start it, then use stopwatch::now() to check time at that moment. it doesn't affect the start time so you can check the loadtime at that moment several times within your script, or run multiple stopwatches.
<?php
class stopwatch
{
private $round = 3;
function __construct ( )
{
$this->start = microtime();
}
function now ( )
{
$start = $this->math($this->start);
$now = $this->math();
return round($now - $start, $this->round);
}
function math ($time = FALSE)
{
if ( !$time ) $time = microtime();
$temp = explode(' ', $time);
return $temp[0] + $temp[1];
}
}
?>
usage:
$stopwatch = new stopwatch();
/* some code */
echo $stopwatch->now();`
sneskid at hotmail dot com
01-Nov-2006 10: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
04-Oct-2006 12: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
16-Sep-2006 10: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 03: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
23-Aug-2006 06:12
`Hey, check this out =]
$mtime = (float)preg_replace('#^0\.([0-9]+) ([0-9]+)$#', '\2.\1', microtime());`
admin at emuxperts dot net
20-Aug-2006 07: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 03: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
16-May-2006 12: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 01: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
30-Apr-2006 08: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
16-Apr-2006 06: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 01: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
21-Mar-2006 03: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
08-Mar-2006 02: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
21-Feb-2006 11: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;
}`
16-Feb-2006 08: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 07:03
`The shortest way for PHP4 users really is
$ts = strtok(microtime(), ' ') + strtok('');`
d dot schneider at 24you dot de
12-Feb-2006 02:30
`Here the short way.
<?
$floattime = array_sum(explode(chr(32), microtime()));
?>`
adiwicaksono at yahoo dot com
03-Feb-2006 07: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
09-Jan-2006 03: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
07-Jan-2006 04: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
29-Nov-2005 09: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
24-Nov-2005 08: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 07: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 07: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 03: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
27-Sep-2005 11: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.`
16-Aug-2005 03: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>
20-Jul-2005 09: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 03: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
17-Jun-2005 03: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 02: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 06: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 03: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()));
?>`
08-Apr-2005 09: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 08: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
14-Mar-2005 06: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
12-Mar-2005 08: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 12: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
23-Feb-2005 08: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 02: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 07: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
20-Jan-2005 07: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 07: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 01: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 06: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());`
28-Sep-2004 11: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
11-Dec-2000 10: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`
add a note
mktime localtime

Last updated: Sat, 27 Jan 2007
show source | credits | stats | sitemap | contact | advertising | mirror sites
Copyright © 2001-2007 The PHP Group
All rights reserved.
This mirror generously provided by: Yahoo! Inc.
Last updated: Sat Mar 10 09:32:46 2007 PST