【问题标题】:Weird Issue on a benchmark in PHPPHP基准的奇怪问题
【发布时间】:2020-07-28 00:43:00
【问题描述】:

我写了这个 sn-p 来测试将字符串转换为整数所需的时间,我在这里尝试这个是为了好玩,但结果非常有趣。

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

?>

结果

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

奇怪的是为什么同样的代码需要更多的时间来运行?

【问题讨论】:

  • 我已经在我的机器上尝试过这个,并且得到了相同的差异,但我认为这可以通过 CPU 架构来解释,因为首先代码被加载到 CPU 中运行,导致从磁盘通过 RAM 到 CPU 需要一些时间。第二个实例不需要通过相同的路径调用过程,而是使用已经存在的东西。我通过将您的测试修改为运行 3 次来验证这一点,分数如下:1.5020370483398E-5 5.0067901611328E-6 5.0067901611328E-6。看看第三次是一样的吗? CPU 已经可以使用一切。
  • @Onyx 我认为我们应该为 avg 基准测试这个代码大约一百万次。

标签: php casting benchmarking microtime


【解决方案1】:

:) 好的@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;
?>

我的结果:

开始时间是上午 09:21:05

结束时间是上午 09:21:12

平均=9.5367527008247E-13

这是在配备 i9-9750 CPU 的华硕 G531T 笔记本电脑上。

对于希望使用此功能的其他人,请勿在您的网页中运行它,只能在 CLI 中使用以下命令: $ php /path/to/test.php 否则你可能会导致浏览器崩溃。它在 CLI 中肯定更快,并且使用换行符而不是换行符对其进行格式化。

【讨论】:

  • 每一个动作,包括回显、计算和连接都需要时间,即使在单引号上使用双引号或 tty 的响应时间,它也会在代码环绕测试时达到一个点需要比你的测试更长的时间,尽管指出 php 有一个操作缓存
  • @LawrenceCherone 绝对是。这更像是一个练习,向 OP 展示了初始加载时间比后续调用相同代码的时间要长得多,而且后续调用的时间也不完全相同。
猜你喜欢
  • 2015-06-19
  • 1970-01-01
  • 2015-12-20
  • 2012-02-02
  • 2011-12-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多