2

What is the best way for getting how long a function takes to run until finish and then storing that number in a variable in PHP ?

How I would think about doing this is get the time right before the function is executed and right after and then take the difference of the former from the latter, but I don't know how get the time in php.

Also, I am trying to get the units to be in tenths and hundredths of second (.42 seconds), hopefully the function takes less than a second to complete so if anyone can help me convert it to those units, i'd appreciate that.

IMUXIxD
  • 1,223
  • 5
  • 23
  • 44

3 Answers3

16

You can do that using microtime().

$start = microtime(true);
for ($x=0;$x<10000;$x++) {}
$end = microtime(true);
echo 'It took ' . ($end-$start) . ' seconds!';
rationalboss
  • 5,330
  • 3
  • 30
  • 50
  • Using microtime is better if available that using time in my example because many functions run in under 1 second. – kainaw Mar 12 '13 at 01:25
2

See "Example #1 Timing script execution with microtime()" in the documentation.

http://docs.php.net/manual/en/function.microtime.php

spencer7593
  • 106,611
  • 15
  • 112
  • 140
0
$time = time();
call_your_function();
$time = time()-$time;
echo "The function took $time seconds to run\n";
kainaw
  • 4,256
  • 1
  • 18
  • 38