如何将PHP微时间显示为最小值:秒


how to display php microtime as min: sec?

我使用以下方法以秒为单位显示代码执行时间:

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

例如,我得到了:

9.809 sec

我想将执行显示为: min : sec,如果最小值为 <1,则为秒单位,如果最小值为>1,则为最小单位。我做单位工作没有问题,但是,微时间以毫秒为单位给出时间,我如何获得以前的输出为:

00:09 sec or 03:50 min

溶液:也:

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

或:

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

谢谢大家

你应该使用一个小的辅助函数:

<?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);
}

输出为:

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

如您所见,如果时间跨度大于 1 小时,您会遇到麻烦,但如果您正在测量脚本的执行时间,这可能不是问题;-)

不使用

日期格式化程序的解决方案 - 自己完成所有操作:

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

注意:如果分钟等于或大于 60,这也有效。 即使您的分钟数大于 99。 后者将需要两个以上的空格(例如,输出120:00 2 小时)。