How to benchmark code to see which runs faster

大城市里の小女人 提交于 2019-12-02 23:51:14

问题


$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?


回答1:


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 . "\n";

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 . "\n";

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




回答2:


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

This is faster because, in DateInterval, you will need to use interval specification which is hard to read.



来源:https://stackoverflow.com/questions/50526182/how-to-benchmark-code-to-see-which-runs-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!