4

I display the code execution time in seconds using:

$time_start = microtime(true);
// code here
$time_end = microtime(true);
$time = ($time_end - $time_start);
$time = number_format((float)$time, 3, '.', '');
echo "Process Time: {$time} sec";

I got for example:

9.809 sec

I want to display the execution as: min : sec , with sec unit if the min <1 and min unit if min >1. I have no issue do the unit job but, microtime gives the time in millisecond how can I get the previous output as:

00:09 sec or 03:50 min

Solution: either:

date('i:s', (int) $time);

or:

$minutes = floor($time / 60);
$seconds = $time % 60;

$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);

echo "Process Time: $minutes:$seconds";

Thanks all

sara
  • 183
  • 1
  • 2
  • 13

2 Answers2

4

You should use a little helper function:

<?php
$times = array(9.123, 230.455, 3601.123);

foreach($times as $time) {
  echo $time . " => " . formatMicrotime($time) . "\n";
}

function formatMicrotime($time) {
   return date('i:s', (int) $time);
}

Output is:

9.123 => 00:09
230.455 => 03:50
3601.123 => 00:01

As you can see, you'll get into trouble if the time span is larger than 1 hour, but that's probably not an issue if you are measuring execution times of your script ;-)

maxhb
  • 8,554
  • 9
  • 29
  • 53
1

a solution without using a date-formatter - doing it all by yourself:

$minutes = floor($time / 60);
$seconds = $time % 60;

$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);

echo "Process Time: $minutes:$seconds";

note: this also works if minutes are equal to or greater than 60. even if your minutes are greater than 99. the latter will need more than two spaces tho (outputs 120:00 for 2 hours for example).

low_rents
  • 4,481
  • 3
  • 27
  • 55