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

search for in the

mktime> <localtime
[edit] Last updated: Fri, 26 Apr 2013

view this page in

microtime

(PHP 4, PHP 5)

microtimeReturn current Unix timestamp with microseconds

Description

mixed microtime ([ bool $get_as_float = false ] )

microtime() returns the current Unix timestamp with microseconds. This function is only available on operating systems that support the gettimeofday() system call.

Parameters

get_as_float

If used and set to TRUE, microtime() will return a float instead of a string, as described in the return values section below.

Return Values

By default, microtime() returns a string in the form "msec sec", where sec is the current time measured in the number of seconds since the Unix epoch (0:00:00 January 1, 1970 GMT), and msec is the number of microseconds that have elapsed since sec expressed in seconds.

If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Changelog

Version Description
5.0.0 The get_as_float parameter was added.

Examples

Example #1 Timing script execution with 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";
?>

Example #2 Timing script execution in PHP 5

<?php
$time_start 
microtime(true);

// Sleep for a while
usleep(100);

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

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

Example #3 microtime() and REQUEST_TIME_FLOAT (as of PHP 5.4.0)

<?php
// Randomize sleeping time
usleep(mt_rand(10010000));

// As of PHP 5.4.0, REQUEST_TIME_FLOAT is available in the $_SERVER superglobal array.
// It contains the timestamp of the start of the request with microsecond precision.
$time microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];

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

See Also

  • time() - Return current Unix timestamp



mktime> <localtime
[edit] Last updated: Fri, 26 Apr 2013
 
add a note add a note User Contributed Notes microtime - [31 notes]
up
4
player27
3 months ago
You can use one variable to check execution $time as follow:

<?php
$time
= -microtime(true);
$hash = 0;
for (
$i=0; $i < rand(1000,4000); ++$i) {
   
$hash ^= md5(substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand(1,10)));
}
$time += microtime(true);
echo
"Hash: $hash iterations:$i time: ",sprintf('%f', $time),PHP_EOL;
?>
up
2
jamie at bishopston dot net
2 years ago
All these timing scripts rely on microtime which relies on gettimebyday(2)

This can be inaccurate on servers that run ntp to syncronise the servers
time.

For timing, you should really use clock_gettime(2) with the
CLOCK_MONOTONIC flag set.

This returns REAL WORLD time, not affected by intentional clock drift.

This may seem a bit picky, but I recently saw a server that's clock was an
hour out, and they'd set it to 'drift' to the correct time (clock is speeded
up until it reaches the correct time)

Those sorts of things can make a real impact.

Any solutions, seeing as php doesn't have a hook into clock_gettime?

More info here: http://tinyurl.com/28vxja9

http://blog.habets.pp.se/2010/09/
gettimeofday-should-never-be-used-to-measure-time
up
1
langpavel at phpskelet dot org
1 year ago
I use this for measure duration of script execution. This function should be defined (and of couse first call made) as soon as possible.

<?php
/**
 * get execution time in seconds at current point of call in seconds
 * @return float Execution time at this point of call
 */
function get_execution_time()
{
    static
$microtime_start = null;
    if(
$microtime_start === null)
    {
       
$microtime_start = microtime(true);
        return
0.0;
    }   
    return
microtime(true) - $microtime_start;
}
get_execution_time();

?>

However it is true that result depends of gettimeofday() call. ([jamie at bishopston dot net] wrote this & I can confirm)
If system time change, result of this function can be unpredictable (much greater or less than zero).
up
0
Anonymous
8 months ago
Observed in php 5.3.3 on CentOS 6 and php 5.3.14 on Amazon Linux 2012.03:

microtime()'s string value is in the format "0.dddddd00 ddddd...".  That is, there's room for 10-ns precision that isn't being used, and the "msec" value is in decimal, not a literal number of microseconds (and *especially* not milliseconds, which is what msec usually stands for) as the documentation might imply.
up
0
Peter Kehl
4 years ago
This function allows you to easily calculate time difference between two points in time without losing the precision.

<?php

   
/**    Calculate a precise time difference.
        @param string $start result of microtime()
        @param string $end result of microtime(); if NULL/FALSE/0/'' then it's now
        @return flat difference in seconds, calculated with minimum precision loss
    */
   
function microtime_diff( $start, $end=NULL ) {
        if( !
$end ) {
           
$end= microtime();
        }
        list(
$start_usec, $start_sec) = explode(" ", $start);
        list(
$end_usec, $end_sec) = explode(" ", $end);
       
$diff_sec= intval($end_sec) - intval($start_sec);
       
$diff_usec= floatval($end_usec) - floatval($start_usec);
        return
floatval( $diff_sec ) + $diff_usec;
    }

?>
up
0
luke at lucanos dot com
4 years ago
Rather than using the list() function, etc. I have found the following code to be a bit cleaner and simpler:
<?php
$theTime
= array_sum( explode( ' ' , microtime() ) );
echo
$theTime;
# Displays "1212018372.3366"
?>
up
-1
thomas
1 year ago
I have been getting negative values substracting a later microtime(true) call from an earlier microtime(true) call on Windows with PHP 5.3.8

Produces negative values
------------------------------
for($i = 0; $i<100; $i++) {
    $x =  microtime(true);
    //short calculation
    $y = microtime(true);
    echo ($y-$x) . "\n"; // <--- mostly negatives
}

Calling usleep(1) seems to work
---------------------------------------
for($i = 0; $i<100; $i++) {
    $x =  microtime(true);
    //short calculation
    usleep(1);
    $y = microtime(true);
    echo ($y-$x) . "\n"; // <--- fixed now
}
up
0
przemek_w
4 days ago
Functions I use to calculate and show page generation time.

<?php

// Insert this block of code at the very top of your page:
function DEBUG_TIME_START(&$start)
{
 
$time = microtime();
 
$time = explode(" ", $time);
 
$time = $time[1] + $time[0];
 
$start = $time;
}

// Place this part at the very end of your page
function DEBUG_TIME_END($start)
{
 
$time = microtime();
 
$time = explode(" ", $time);
 
$time = $time[1] + $time[0];
 
$finish = $time;
 
$totaltime = ($finish - $start);
  return
sprintf ("This page took %.2f seconds to load.\n", $totaltime);
}

?>

Usage:

<?php

DEBUG_TIME_START
($start);

/* Do stuff.... */

print DEBUG_TIME_END($start);

?>

Example output:

This page took 22.41 seconds to load.
up
0
Robin Leffmann
2 years ago
While doing some experiments on using microtime()'s output for an entropy generator I found that its microsecond value was always quantified to the nearest hundreds (i.e. the number ends with 00), which affected the randomness of the entropy generator. This output pattern was consistent on three separate machines, running OpenBSD, Mac OS X and Windows.
 
The solution was to instead use gettimeofday()'s output, as its usec value followed no quantifiable pattern on any of the three test platforms.
up
0
Anonymous
2 years ago
that related to the prescedence of the . operator

<?php
# normal prescedence
$a = "te" .   1 - 2   . "st"; # ((te . 1) - 2 ) . st ==> -2st
$b = "te" .   1 + 2   . "st"; # ((te . 1) + 2 ) . st ==>  2st

# modified prescedence
$c = "te" . ( 1 - 2 ) . "st"; # te . ( 1 - 2 ) . st ==> te-1st
$d = "te" . ( 1 + 2 ) . "st"; # te . ( 1 + 2 ) . st ==> te3st

var_dump( $a, $b );
var_dump( $c, $d );
up
0
Andris
2 years ago
I wrote a class which allows to time execution of php scripts very easily. You can even time multiple separate blocks and then get the total time at the end.

The class is pretty long so I won't post it here, but here's the link:
http://codeaid.net/php/calculate-script-execution-time-(php-class)

An quick usage example:
<?php
for ($i = 0; $i < 100; $i++) {
    
// calculate the time it takes to run fx()
    
Timer::start();
    
fx();
    
Timer::stop();
 
    
fy();
 
    
// calculate the time it takes to run fz()
    
Timer::start();
    
fz();
    
Timer::stop();
}
 
print
Timer::get();
?>
up
0
bleakwind at gmail dot com
3 years ago
Check Program runtime:
<?php

class bwruntime
{
    var
$timestart;
    var
$digits;

    function
bwruntime($digits = "")
    {
       
$this->timestart    = explode (' ', microtime());
       
$this->digits       = $digits;
    }

    function
totaltime()
    {
       
$timefinish         = explode (' ', microtime());
        if(
$this->digits == ""){
           
$runtime_float  = $timefinish[0] - $this->timestart[0];
        }else{
           
$runtime_float  = round(($timefinish[0] - $this->timestart[0]), $this->digits);
        }
       
$runtime = ($timefinish[1] - $this->timestart[1]) + $runtime_float;
        return
$runtime;
    }
}
?>
up
0
thawootah
3 years ago
Want to make sure your script doesn't time out on large updates? Say you're doing a poor mans cron job or working with large amounts of data in loop and the user begins to hang too long. Instead of them giving up and leaving you can break the loop when it reaches a set time and still display data.

Here's a simple handy dandy loop timer rounded to second.
<?php
$starttime
= round(microtime(true));
$totaltime  = 0;
$maxtime = 5; //seconds
for ($i = 1; $i <= 20; $i++) {  /// 20 loops 1 sec each

       
usleep(1000000);

    if(
$totaltime < $maxtime){
   
$currenttime = round(microtime(true));
   
$totaltime = $totaltime + ($currenttime -$starttime);
       
//update and continue
   
echo  $i.'<br>';
   
    }else{
       
// stop updating or display not updated data.
   
break;
    }
}

?>
up
0
gomodo at free dot fr
3 years ago
Need a mini benchmark ?
Use microtime with this (very smart) benchmark function :

mixed mini_bench_to(array timelist[, return_array=false])
return a mini bench result

-the timelist first key must be 'start'
-default return a resume string, or array if return_array= true :
'total_time' (ms) in first row
details (purcent) in next row

example :
<?php
unset($t);    // if previous used

//-- zone to bench
$t['start'] = microtime(true);
$tab_test=array(1,2,3,4,5,6,7,8);
$fact=1;
$t['init_values'] = microtime(true);
foreach (
$tab_test as $key=>$value)
{
   
$fact=$fact*$value;
}
$t['loop_fact'] = microtime(true);
echo
"fact = ".$fact."\n";
//-- END zone to bench

echo "---- string result----\n";
$str_result_bench=mini_bench_to($t);
echo
$str_result_bench; // string return
echo "---- tab result----\n";
$tab_result_bench=mini_bench_to($t,true);
echo
var_export($tab_result_bench,true);
?>
this example return:

---- string result----
total time : 0.0141 ms
start -> init_values : 51.1 %
init_values -> loop_fact : 48.9 %
---- tab result----
array (
  'total_time' => 0.0141,
  'start -> init_values' => 51.1,
  'init_values -> loop_fact' => 48.9,
)

The function to include :

<?php
function mini_bench_to($arg_t, $arg_ra=false)
  {
   
$tttime=round((end($arg_t)-$arg_t['start'])*1000,4);
    if (
$arg_ra) $ar_aff['total_time']=$tttime;
    else
$aff="total time : ".$tttime."ms\n";
   
$prv_cle='start';
   
$prv_val=$arg_t['start'];

    foreach (
$arg_t as $cle=>$val)
    {
        if(
$cle!='start')   
        {
           
$prcnt_t=round(((round(($val-$prv_val)*1000,4)/$tttime)*100),1);
            if (
$arg_ra) $ar_aff[$prv_cle.' -> '.$cle]=$prcnt_t;
           
$aff.=$prv_cle.' -> '.$cle.' : '.$prcnt_t." %\n";
           
$prv_val=$val;
           
$prv_cle=$cle;
        }
    }
    if (
$arg_ra) return $ar_aff;
    return
$aff;
  }
?>
up
0
singh206 at gmail dot com
4 years ago
<?php
class StopWatch {
    public
$total;
    public
$time;
   
    public function
__construct() {
       
$this->total = $this->time = microtime(true);
    }
   
    public function
clock() {
        return -
$this->time + ($this->time = microtime(true));
    }
   
    public function
elapsed() {
        return
microtime(true) - $this->total;
    }
   
    public function
reset() {
       
$this->total=$this->time=microtime(true);
    }
}

$stopwatch = new StopWatch();
usleep(1000000);
echo
"Checkpoint 1: ".$stopwatch->clock()." seconds<br />";

usleep(1000000);
echo
"Checkpoint 2: ".$stopwatch->clock()." seconds<br />";

echo
"Total Elapsed: ".$stopwatch->elapsed()." seconds<br />";
?>
up
0
christ dot boris at nospam gmail dot com
4 years ago
Hi, I made a function to get the generation page time :

<?php
function gentime() {
    static
$a;
    if(
$a == 0) $a = microtime(true);
    else return (string)(
microtime(true)-$a);
}
?>

(You can add a round() to the return value if you want)

Use :

<?php
# you should include your libraries/conf files here (including the gentime function)
gentime();

# your source code here

echo 'Generated in '.gentime().' seconds.'
?>
up
0
pascalxusPLEASENOSPAM at yahoo dot com
4 years ago
I wanted to find out whether echo would be quicker in small chunks or one large chunk to test the theory mentioned in the previous post.  The following experiment shows that there is no significant performance difference, in terms of execution time elapsed, between the two methods of using echo.  I ran two test cases, one with a string that is 100000 bytes long and another with a string length of 1000000.  The source code follows below.

<?php

function echobig($string, $bufferSize = 8192)
{
   
$splitString = str_split($string, $bufferSize);

    foreach(
$splitString as $chunk)
        echo
$chunk;
}

global
$dat;
$dat = "";

function
testit()
{
global
$dat;
$data = "";

for(
$a = 0; $a <= 1000000; $a += 1 ) $data .= "a";

$u1= microtime(true);
echobig( $data );
$u2= microtime(true);
echo
$data;
$u3= microtime(true);

$diff = $u2 - $u1;
$diff2= $u3 - $u2;
$dat .= "$diff2 $diff    $u2  $u1\r\n";
}

$i = 0;
while(
$i < 5 )
{
 
testit(); $i += 1;
}

global
$dat;
$fp = fopen( "../Data/results.txt", "w" );
fwrite( $fp, $dat );
fclose( $fp );
?>

You can run the above experiment yourself or you can look at my test data.  I got some test data here:  http://www.codesplunk.com/examples/echo.html
up
0
kpsimoulis [at] genatec
4 years ago
This function is very useful for putting a start and end point in your page to find out where is the delay.

<?php

$start
= microtime(true);
// My source code here
$end = microtime(true);

echo
$end."-".$start."=".($end - $start). " seconds";

?>

If you try this example above (without any source code between the start and the end point). You will get an ugly value, something like:
1212690530.4132-1212690530.4132=8.1062316894531E-6 seconds

You will wonder why you get this because both numbers seem to be equal. Well this is because there is a hidden precision that we are not able to see.

To solve this problem I made a new function:

<?php

function my_microtime($precision = 4)
{
    return
round(microtime(true),4);
}

$start = microtime(true);
// My source code here
$end = microtime(true);

echo
$end."-".$start."=".substr(($end - $start),0,5). " seconds";

?>

It would be useful if they add another parameter for precision in this function or at least another boolean that will not include the hidden precision.
You can read more about the hidden precision in http://php.net/float
up
0
admin at emuxperts dot net
6 years ago
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
?>
up
0
EdorFaus
6 years ago
Of the methods I've seen here, and thought up myself, to convert microtime() output into a numerical value, the microtime_float() one shown in the documentation proper(using explode,list,float,+) is the slowest in terms of runtime.

I implemented the various methods, ran each in a tight loop 1,000,000 times, and compared runtimes (and output). I did this 10 times to make sure there wasn't a problem of other things putting a load spike on the server. I'll admit I didn't take into account martijn at vanderlee dot com's comments on testing accuracy, but as I figured the looping code etc would be the same, and this was only meant as a relative comparison, it should not be necessary.

The above method took on average 5.7151877 seconds, while a method using substr and simply adding strings with . took on average 3.0144226 seconds. rsalazar at innox dot com dot mx's method using preg_replace used on average 4.1819633 seconds. This shows that there are indeed differences, but for normal use noone is going to notice it.

Note that the substr method mentioned isn't quite the one given anonymously below, but one I made based on it:
<?php
$time
=microtime();
$timeval=substr($time,11).substr($time,1,9);
?>

Also worth noting is that the microtime_float() method gets faster, and no less accurate, if the (float) conversions are taken out and the variables are simply added together.

Any of the methods that used + or array_sum ended up rounding the result to 2 digits after the decimal point, while (most of) the ones using preg_replace or substr and . kept all the digits.

For accurate timing, since floating-point arithmetic would lose precision, I stored microtime results as-is and calculated time difference with this function:
<?php
function microtime_used($before,$after) {
    return (
substr($after,11)-substr($before,11))
        +(
substr($after,0,9)-substr($before,0,9));
}
?>

For further information, the script itself, etc, see http://edorfaus.xepher.net/div/convert-method-test.php
up
0
radek at pinkbike com
7 years ago
A lot of the comments here suggest adding in the following way:  (float)$usec + (float)$sec
Make sure you have the float precision high enough as with the default precision of 12, you are only precise to the 0.01 seconds. 
Set this in you php.ini file.
        precision    =  16
up
0
vladson at pc-labs dot info
7 years ago
I like to use bcmath for it
<?php
function micro_time() {
   
$temp = explode(" ", microtime());
    return
bcadd($temp[0], $temp[1], 6);
}

$time_start = micro_time();
sleep(1);
$time_stop = micro_time();

$time_overall = bcsub($time_stop, $time_start, 6);
echo
"Execution time - $time_overall Seconds";
?>
up
0
php at washboardabs dot net
8 years ago
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.
up
-1
final at skilled dot ch
7 months ago
Note that php's microtime() and time() function might not necessarily return the same time. I don't know why this is the case (I assume microtime() and time() use different kernel functions). This is reproduceable under both linux and windows (I only tested intel and ARM CPUs though):

for linux, use this:
<?php
for ($i = 0; $i < 1000000; $i++)
{
  if (
time() < floor(microtime(true))) {
    echo
".";
  }
}
?>
if microtime and time would switch to the next second at exactly the same time, you should never see any . out of this script. However, it does produces some . under both linux and windows.
up
-1
junk at gieson dot com
8 months ago
To return a timestamp as an integer with milliseconds:

(Same as javascript and actionscript)

-------------------------------
PHP
-------------------------------
<?php
function getTimestamp(){
   
$seconds = microtime(true); // false = int, true = float
   
return round( ($seconds * 1000) );
}

print (
"<pre>");
print (
time()."<br>");
print (
microtime(true)."<br>");
print (
getTimestamp()."<br>");
print (
"</pre>");
?>

-------------------------------
Javascript / Actionscript
-------------------------------
function getTimestamp(){
    var d = new Date();
    return Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()).valueOf();
}
up
-1
maxim at inbox dot ru
10 months ago
Same as 'langpavel at phpskelet dot org' but in one row:
<?php
function get_execution_time()
{
    static
$microtime_start = null;
   
        return
$microtime_start === null ? $microtime_start = microtime(true) : microtime(true) - $microtime_start;

}

get_execution_time();
?>
up
-1
Harald Hanek
2 years ago
As float with more accuracy.

<?php
function getmicrotime($e = 7)
{
    list(
$u, $s) = explode(' ',microtime());
    return
bcadd($u, $s, $e);
}
echo
getmicrotime();
?>
up
-1
leonardonobre at ibest dot com dot br
2 years ago
Convert date type MySQL to Brazilian (i.e: 2010-07-23 to 23/07/2010);

<?php
$date_brazilian
= date("Y-m-d",microtime($_REQUEST[data_inicial]));
?>

The var $_REQUEST[data_inicial] = 23/07/2010 and convert to microtime (Unix TimeStamp) and the function date convert to format "Y-m-d".

Léo
up
-1
strata_ranger at hotmail dot com
3 years ago
Another version of a stopwatch-style function, this one with the following features:
- Can evaluate any function (callback) with any arbitrary arguments
- Can specify the # of iterations to run

The obvious caveat is of course to take the return value with a grain of salt, especially since this one doesn't run in the tightest loop possible.  A little eval() work could probably fix that, but in the meantime calling this function with no arguments will make it establish a reference point (using pi() ) to measure subsequent calls against -- sort of like hitting the "zero" button on a food scale.

<?php
function stopwatch()
// stopwatch([$limit], [$callback], [$args ... ])
// $limit - # of iterations to run
// $callback - function to time
// $args - arguments for function
//
{
  static
$zero = 0;
  static
$limit = 99999;

 
$args = func_get_args() + Array(null);
 
 
// Check for # iterations, assign for future calls
 
if (is_integer($args[0])) $max = min(array_shift($args), 999999); else $max = $limit;
  if (
$max != $limit)
  {
   
$limit = $max;
   
$zero = 0;
  }
  if (isset(
$args[0])) $callback = array_shift($args); else $callback = null;

  if (
is_null($callback))
  {
   
// Use a very small function as a reference point
   
$callback = 'pi';
   
$zero = null;
  } 

 
// Ensure a valid callback
 
if (!is_callable($callback, false, $name)) return null;
  if (
$name == __FUNCTION__) return null;

 
// The actual loop
 
$st = explode(' ',microtime());
  for(
$cx=0$cx<$max$cx++)
  {
   
call_user_func_array($callback, $args);
  }

 
// Final calculations
 
$t = explode(' ', microtime());
 
$t[0] -= $st[0];
 
$t[1] -= $st[1];
 
  if (
is_array($zero)) // Use previous reference point
 
{
   
$t[0] -= $zero[0];
   
$t[1] -= $zero[1];
  }
  elseif (
is_null($zero)) // or establish a new one
 
{
   
$zero = $t;
    return;
  }
 
  if (
$t[0] < 0) // Ensure microseconds are always positive
 
{
   
$t[0]++; $t[1]--;
  }

 
// Done
 
return "$t[1] + $t[0]s"
}

function
faster()
{
  return;
}

function
slower()
{
  return
fmod(5,2);
}

echo
"<p>Comparing two functions...</p>";
var_dump(stopwatch('faster'));
var_dump(stopwatch('slower'));

echo
"<p>Comparing 100,000 iterations of two functions...";
var_dump(stopwatch(100000, 'faster'));
var_dump(stopwatch('slower'));

echo
"<p>Run a single function 500 times...</p>";
var_dump(stopwatch(500));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));

echo
"<p>Run a single function 555,555 times...</p>";
var_dump(stopwatch(555555));
var_dump(stopwatch('max', 1, 2, 3, 4, 5));

echo
"<p>Fail sanity test...</p>";
var_dump(stopwatch('stopwatch')); // Attempt to time itself!
?>
up
-1
SimonB
4 years ago
Here is a simple way to measure the clients connection speed (assuming the server is able to supply fast enough). It measures how much data is transfered in one second and reports the result.

I needed to measure this to offer sensible defaults for selecting live streams at different bitrates for a webcasting application.

<?php
function measure_kbps()
{
 
//Return the unix timestamp + microseconds
 
function micro_time()
  {
   
$timearray = explode(" ", microtime());
    return (
$timearray[1] + $timearray[0]);
  }

 
//Prepare a 1kB chunk to send
 
for ($i=0; $i<1023; $i++) $chunk.='A';
 
$chunk.='\n';
 
//Hide what happens next
 
echo "<!-- ";
 
//Keep sending 1 kB chunks for 1 second
 
flush();
 
$count=0;
 
$starttime = micro_time();
  do
  {
    echo
$chunk;
   
$count++;
   
flush();
   
$endtime = micro_time();
   
$totaltime = $endtime - $starttime;
   
$totaltime = round($totaltime,5);
  } while (
$totaltime < 1);
  echo
" -->\n";
 
//Return how many kb were sent
 
return ($count * 8);
}
$kbps=measure_kbps();
$mbps=$kbps / 1024;
if (
$mbps > 1 ) echo "Your speed is $mbps Mbps.<br />";
  else echo
"Your speed is $kbps Kbps.<br />";
?>
up
-2
mcq at supergamez dot hu
12 years ago
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

 
show source | credits | stats | sitemap | contact | advertising | mirror sites