|
 |
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++) {
}
$time_end = getmicrotime();
$time = $time_end - $time_start;
echo "Ничего не делал $time секунд\n";
$time_start = microtime(1);
for ($i=0; $i < 1000; $i++) {
}
$time_end = microtime(1);
$time = $time_end - $time_start;
echo "Ничего не делал $time секунд\n";
?>
|
|
См. также описание функции time().
microtime
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);
}
}
$t = new Timer();
$t->start();
sleep(1);
var_dump($t->fetch()); $t->start();
$t->pause();
sleep(1);
$t->unpause();
var_dump($t->fetch()); ?>
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
function microtimestamp($id='') {
$stamp = gettimeofday();
if ($id=='id') { $divby=100000; } else { $divby=1000000; }
$stamp = $stamp['sec'] + $stamp['usec'] / $divby ;
$stamp = str_replace('.','',$stamp);
$stamp = substr($stamp.'00000',0,15) ; return $stamp;
}
echo '<b>'.time()." <- time()</b><br>\n";
while ( $cnt < 11 ) {
$cnt++;
echo microtimestamp() . "<br>\n";
}
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
$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];
$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 ) {
if ( !empty( $GLOBALS['start_script_runtime'] ) ) {
list($msec, $sec) = explode(" ", microtime());
echo round(($sec + $msec) - $GLOBALS['start_script_runtime'], $round);
} else {
list($msec, $sec) = explode(" ", microtime());
$GLOBALS['start_script_runtime'] = $sec + $msec;
}
}
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 {
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();
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();
?>
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';
?>
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
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();
usleep(100);
$time_end = microtime_float();
$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
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}==='"')){ $str=substr($str,0,$i).substr($str,$i+1);
$i--;
}
return $str;
}
$runtimes=1000;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());
$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(); ?>
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;
$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
$CHRONO_STARTTIME = 0;
define("RET_TIME", "ms"); or "s" for seconds
function chronometer()
{
global $CHRONO_STARTTIME;
$now = microtime(TRUE); 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) {
$retElapsed = round($now * $malt - $CHRONO_STARTTIME * $malt, $round);
$CHRONO_STARTTIME = $now;
return $retElapsed;
} else {
$CHRONO_STARTTIME = $now;
return 0;
}
}
?>
It can be used like this:
<?php
chronometer();
echo chronometer(); echo chronometer(); ?>
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
$timestart = microtime();
<<some code>>
$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
| |