0

I try calculate time of an act in second with 2 decimals.

protected function microtimeFormat($data)
    {
        $duration = microtime(true) - $data;
        $hours = (int)($duration/60/60);
        $minutes = (int)($duration/60)-$hours*60;
        return $seconds = $duration-$hours*60*60-$minutes*60;

    }

this method get start time as $data...and get back it an int second

for example it return 2second.

I try get second with 2 decimals ...

protected function microtimeFormat($data,$format=null,$lng=null)
    {
        $duration = microtime(true) - $data;
        $hours = (float)($duration/60/60);
        $minutes = (float)($duration/60)-$hours*60;
        $seconds = $duration-$hours*60*60-$minutes*60;
        return number_format((float)$seconds, 2, '.', '');
    }

but it return me 0.00 for short time

alia an
  • 103
  • 1
  • 7

2 Answers2

0

I think your issue comes from the (float) conversion to $hours and $minutes. When you do so you don't save the decimal part of each so your calculation of $seconds always give 0. Convert to int so you actually save in $hours and $minutes the actual number of seconds they each represent. And the remainder goes to $seconds.

protected function microtimeFormat($data,$format=null,$lng=null)
{
    $duration = microtime(true) - $data;
    $hours = (int)($duration/60/60);
    $minutes = (int)($duration/60)-$hours*60;
    $seconds = $duration-$hours*60*60-$minutes*60;
    return number_format((float)$seconds, 2, '.', '');
}

$start = microtime(TRUE);
sleep(1);
$delay = $this->microtimeFormat($start);
var_dump($delay);

This gives me:

string(4) "1.01"
shadock
  • 376
  • 3
  • 9
  • if i do `sleep(70);` i get result: `string(5) "10.00"` – phpJs Aug 09 '17 at 18:38
  • I'm new to php, not new to programming. Although your code just proved very useful to me, this kind of code is the reasons people talk bad about PHP. thanks anyway – Nick Dec 08 '17 at 14:06
0

I use this form to generate a time in seconds, eg 1.20

$start = microtime(true);
for ($i=0; $i < 10000000; $i++) { 
    # code...
}
$end = microtime(true);

echo "<br>" . $time = number_format(($end - $start), 2);
// We get this: 1.20

An example comparing the performance of 2 functions of PHP:

define( 'NUM_TESTS', 1000000);

$start = microtime(true);

for( $i = 0; $i < NUM_TESTS; $i++)
{
    mt_rand();
}

$end = microtime(true) - $start;
echo 'mt_rand: ' . number_format(($end), 2) . "\n";

$start = microtime(true);

for( $i = 0; $i < NUM_TESTS; $i++)
{
    uniqid();
}

$end = microtime(true) - $start;
echo 'uniqid: ' . number_format(($end), 2) . "\n";
// We get this: mt_rand: 0.12 uniqid: 2.06
Learning and sharing
  • 1,231
  • 2
  • 20
  • 38