Weird Issue on a benchmark in PHP

55 Views Asked by At

I have wrote this snippet to test the time that it takes to cast a string to integer and I tried this one here for fun but the result was so interesting.

<?php
$s = "123456789";
$t = microtime(true);
$data["HI"] = $s;
echo json_encode($data);
$time1 = (microtime(true) - $t);

$t = microtime(true);
$data2["HI"] = $s;
echo json_encode($data2);
$time2 = (microtime(true) - $t);

if($time1 > $time2) {
  echo "yes";
  echo $time1;
  echo $time2;
}

?>

Result

yes
$time1 => 1.2874603271484E-5
$time2 => 3.0994415283203E-6

The weird thing is why would the same code take more time to run?

1

There are 1 best solutions below

2
Onyx On

:) ok @Mahdi Bagheri

 <?php
function dowork(){
$s = rand(100000,999999);
$t = microtime(true);
$data["HI"] = $s;
$j= json_encode($data);
$time1 = (microtime(true) - $t);
return $time1;
}
$avg = 0; $limit = 1000000; $start = date("h:i:sa");

  for($x=1 ;  $x<=$limit; $x++){
      $avg = ($avg + dowork())/$x;
      print "Iteration: ".$x. " Average = ". $avg ."\r\n";
}

print "Starting time is " . $start."\r\n";
print "Ending time is " . date("h:i:sa")."\r\n";
print "Average=".$avg;
?>

My results:

Starting time is 09:21:05am

Ending time is 09:21:12am

Average=9.5367527008247E-13

This is on an Asus G531T laptop with i9-9750 CPU.

For anyone else who wishes to play with this, DON'T run it in your web page, only at the CLI with the likes of : $ php /path/to/test.php or you could crash the browser. It is certainly faster at CLI, and formatted for it with line feeds rather than breaks.