如何对代码进行基准测试以查看运行速度更快 [英] How to benchmark code to see which runs faster

查看:117
本文介绍了如何对代码进行基准测试以查看运行速度更快的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$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');

任何人都可以告诉我,在php文件中进行大量操作时,哪一种更快,更推荐并且占用更少的内存。我认为它的DateInterval PID。有经验的开发人员吗?

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?

推荐答案

要进行基准测试,可以使用 microtime()

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";

此输出为:

modify: 0.039623975753784 
interval: 0.036103963851929

如您所见,在每次执行10,000次计算之后,DateInterval是更快的代码。但是,这就是我所说的微优化!没什么区别!

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!

在这里查看它的工作 https: //3v4l.org/pCecn

这篇关于如何对代码进行基准测试以查看运行速度更快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆