0

Am running a script and it determines my execution time. I get a negative when it calculates the time. I would like it to give me a positive when it executes.

<?php
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
echo "executed";

$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
$minutes = (int)($totaltime/60)-$hours*60;
echo "This page was created in ".$minutes." minute/s";

?>
saiyan101
  • 610
  • 4
  • 12
  • 28

1 Answers1

5

The microtime() is returning as a String. Try passing in true to make it return a floating point value. This would also shorten your code to:

$starttime = microtime(true);
echo "Executed";

$endtime = microtime(true);
$totaltime = $endtime - $starttime;
$minutes = intval(ceil(($endtime - $starttime) / 60));
echo "This page was created in " . $minutes . " minute(s)";
...

Resource: http://www.php.net/microtime

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
  • 1
    Glad to know my habit of writing it like this actually has a point! – Rich Bradshaw Mar 07 '13 at 14:20
  • Am getting a negative when I start going to minutes – saiyan101 Mar 07 '13 at 14:37
  • @saiyan101 - What exactly are you getting? Also, where is $hours set? (I'm assuming that you're getting the $minutes part from http://stackoverflow.com/questions/6468127/microtime-to-seconds-or-hours-or-min-conversion?rq=1) Also, what version of PHP are you using? – Chris Forrence Mar 07 '13 at 14:43
  • This is what I get `-474942508 minutes` as my result. And yes am using minutes part from the link you supplied. Am using phpDesktop to run my app. – saiyan101 Mar 07 '13 at 14:57
  • @saiyan101 - Ok, try this instead to set minutes (you never said that you were using the `$hours` variable, so that might be causing problems: `$minutes = intval(ceil(($endtime - $starttime) / 60));` – Chris Forrence Mar 07 '13 at 15:02