timing php functions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
jaymoore_299
Forum Contributor
Posts: 128
Joined: Wed May 11, 2005 6:40 pm
Contact:

timing php functions

Post by jaymoore_299 »

I want to measure how long a certain section of code takes to complete, any ideas on how this is possible?
IAD
Forum Commoner
Posts: 42
Joined: Wed Dec 28, 2005 12:36 pm
Location: Israel, Soon Canada :)

Post 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.
foobar
Forum Regular
Posts: 613
Joined: Wed Sep 28, 2005 10:08 am

Post 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:
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post 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";
?>
User avatar
onion2k
Jedi Mod
Posts: 5263
Joined: Tue Dec 21, 2004 5:03 pm
Location: usrlab.com

Post by onion2k »

alternatively.. xdebug.org
Post Reply