php测试代码执行消耗的内存和时间
在php中要测试代码执行消耗的内存和时间我们可以直接使用俩函数,microtime 和 memory_get_usage就可以了,下面我来给大家介绍介绍。
我们先来看看microtime 和 memory_get_usage函数用法吧
含义和用法
microtime() 函数返回当前 Unix 时间戳和微秒数。
语法:microtime(get_as_float),get_as_float如果给出了get_as_float参数并且其值等价于 TRUE,该函数将返回一个浮点数。
代码实例如下:echo(microtime());
输出:0.25139300 1138197510
一,函数原型:int memory_get_usage ([ bool $real_usage=false ] )
二,版本兼容:PHP 4 >= 4.3.2,PHP 5
三,基础用法与实例
1,获取当前的内存消耗量,代码如下:
<?php echo memory_get_usage(); $var = str_repeat(www . phprm . com, 10000); echo memory_get_usage(); unset($var); echo memory_get_usage(); ?>
结果输出:62328 122504 62416
说明:memory_get_usage() 函数输出的数值为 bytes 单位
2,格式化 memory_get_usage() 结果以 KB 为单位输出,代码如下:
<?php function convert($size) { $unit = array('b','kb','mb','gb','tb','pb'); return @round($size / pow(1024, ($i = floor(log($size, 1024)))) , 2) . ' ' . $unit[$i]; } echo convert(memory_get_usage(true)); ?>
265KB,好了两个函数基本介绍完了,下面我来看一个测试实例:
<?php $t1 = microtime(true); $m1 = memory_get_usage(true); echo fixByte($m1) . '<br />'; /*↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓*/ /*↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑*/ $t2 = microtime(true); $m2 = memory_get_usage(true); echo '<br />' . fixByte($m2) . '<br />'; echo '<hr >'; echo 'time ' . round(($t2 - $t1) , 4) . '<br />'; echo 'mem ' . fixByte($m2 - $m1) . '<br />'; /** * 格式化字节为合适的数值 * @param int $byte 字节数 * @param string $string 格式化的可读性强的字节数 */ function fixByte($byte, $string = true, $dot_num = 9) { $ret = array( 'data' => $byte, 'danwei' => 'Byte', ); if ($byte < 1024) { } else if ($byte < 1024 * 1024) { $ret['data'] = round($byte / 1024, $dot_num); $ret['danwei'] = 'K'; } else if ($byte < 1024 * 1024 * 1024) { $ret['data'] = round($byte / (1024 * 1024) , $dot_num); $ret['danwei'] = 'M'; } else if ($byte < 1024 * 1024 * 1024 * 1024) { $ret['data'] = round($byte / (1024 * 1024 * 1024) , $dot_num); $ret['danwei'] = 'GB'; } else if ($byte < 1024 * 1024 * 1024 * 1024 * 1024) { $ret['data'] = round($byte / (1024 * 1024 * 1024 * 1024) , $dot_num); $ret['danwei'] = 'TB'; } if ($string) { $ret = $ret['data'] . ' ' . $ret['danwei']; } return $ret; } ?>
本文链接:http://www.phprm.com/develop/fs1105.html
收藏随意^^请保留教程地址.