dongxun2089 2018-05-25 09:43
浏览 28
已采纳

如何对代码进行基准测试以查看运行速度更快

$datetime = new DateTime('2013-01-29');
$datetime->modify('+1 day');
echo $datetime->format('Y-m-d H:i:s');

$datetime = new DateTime('2013-01-29');
$datetime->add(new DateInterval('P1D'));
echo $datetime->format('Y-m-d H:i:s');

Can anyone tell me which is faster, recommended and takes less memory in huge operations in php file. I think its DateInterval PID. Any experienced developer?

  • 写回答

2条回答 默认 最新

  • doujiaochan7317 2018-05-25 11:09
    关注

    To benchmark code, you can use microtime()

    http://php.net/manual/en/function.microtime.php

    <?php
    
    echo 'modify: ';
    $time = microtime(1);
    for ($x = 0; $x < 10000; $x++) {
        $datetime = new DateTime('2013-01-29');
        $datetime->modify('+1 day');
    }
    echo $datetime->format('Y-m-d H:i:s'); 
    $end = microtime(1);
    $time = $end - $time;
    echo $time . "
    ";
    
    echo 'interval: ';
    $time = microtime(1);
    for ($x = 0; $x < 10000; $x++) {
        $datetime = new DateTime('2013-01-29');
        $datetime->add(new DateInterval('P1D'));
    }
    $end = microtime(1);
    $time = $end - $time;
    echo $time . "
    ";
    

    This outputs :

    modify: 0.039623975753784 
    interval: 0.036103963851929
    

    As you can see, after performing the calculation 10,000 times on each, DateInterval is the faster code. However, this is what I would call a microoptimisation! There isn't much difference!

    See it working here https://3v4l.org/pCecn

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题