Page 1 of 1

timing php functions

Posted: Wed Dec 28, 2005 11:54 pm
by jaymoore_299
I want to measure how long a certain section of code takes to complete, any ideas on how this is possible?

Posted: Thu Dec 29, 2005 1:50 am
by IAD
Hey,

If you want to measure the time that takes to the page to start, use: microtime();

I'll give you an example:

Code: Select all

<?Php
  $time_started = microtime();

           sleep(100);

   $time_ended = microtime();

       $time_loaded = $time_ended - $time_started; 

          print $time_loaded; // will print someting like 0.2154854213
?>
What i did is taking the microtime() function, now i know the starting time of the page's actions, that i let the browser stop working for 100 [not seconds!!!] and that i used again with the function microtime(); to check when it stoped.

This code gave me the exactly time that took the browser to load this page.

If the number of second is to long, than use round(); or other function that will make the number shorter.

[I didn't check the code, just wrote it, so check it]


Hope i helped, Tal.

Posted: Thu Dec 29, 2005 6:03 am
by foobar
Note: microtime() may not work on windows.

Use this instead:

Code: Select all

function getmicrotime(){
  $time = gettimeofday();
  return $time['sec'].str_pad($time['usec'], 6, 0, STR_PAD_LEFT);
}
BTW, I didn't create that function, I just ripped it off some anonymous contributor to the PHP Manual. :wink:

Posted: Thu Dec 29, 2005 11:41 am
by josh
From the manual

Code: Select all

<?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";
?>

Posted: Thu Dec 29, 2005 12:28 pm
by onion2k
alternatively.. xdebug.org