Home > php教程 > PHP源码 > body text

[PHP]简单的耗时内存记录类

PHP中文网
Release: 2016-05-25 16:59:04
Original
1381 people have browsed it

新手瞎写的,欢迎扩展或批评指导。
目前仅记录耗时与内存占用,还有其他需要记录的属性吗?
有些注释部分标记了疑问,欢迎高人解答。

  1. 耗时内存记录类

<?php
 /**
 * 耗时内存记录类,记录代码消耗
 */
class Test
{
    private static $d = array();//用于存储记录
 
    public static function m($str=""){//记录时间与内存,m表示mark
        $o=array();
        if($str)
            $o[&#39;title&#39;]= $str;
        else{
            $o[&#39;title&#39;]=&#39;第&#39;.(count(self::$d)+1).&#39;部分&#39;;
        }
        list($usec,$sec)=explode(" ",microtime());
        $o[&#39;time&#39;]=(float)$usec+(float)$sec;//这行是copy来的,不加(float)会怎么样?
        $o[&#39;memory&#39;]= memory_get_usage();
        self::$d[]=$o;
    }
 
    public static function show(){//输出
        self::m();
        $arr =& self::$d;
        $r=null;    
        $n=count($arr)-1;
        for($i=0; $i<$n; $i++){
            $r.=$arr[$i][&#39;title&#39;].&#39;<br />
耗时增加:&#39;. number_format(($arr[$i+1][&#39;time&#39;] - $arr[$i][&#39;time&#39;]),6) .&#39;<br />
内存增加:&#39;.( $arr[$i+1][&#39;memory&#39;] - $arr[$i][&#39;memory&#39;] ).&#39;<br /><br />&#39;;
        }
        $r.=&#39;汇总<br />
总耗时:&#39;. number_format(($arr[$n][&#39;time&#39;] - $arr[0][&#39;time&#39;]),6) .&#39;<br />
总内存:&#39;.( $arr[$n][&#39;memory&#39;] - $arr[0][&#39;memory&#39;] ).&#39;<br /><br />&#39;;
        echo $r;
    }
}
Copy after login

2.使用方法

<?php
$arr1=$arr2=$arr3=array();
$i=$j=$n=9999;
 
Test::m(&#39;测试 $arr1[]=$i&#39;);
while($i--)
    $arr1[]=$i;
 
Test::m(&#39;测试 array_push($arr2,$j)&#39;);
while($j--)
    array_push($arr2,$j);
 
Test::m(&#39;测试 $arr3[$n]=$n &#39;);
while($n--)
    $arr3[$n]=$n;
 
 
Test::show();//求教,有没有简单办法节省这行代码,静态类可以用析构函数自动调用吗?
 
 
 
/*
输出
 
测试 $arr1[]=$i
耗时增加:0.002209
内存增加:1412040
 
测试 array_push($arr2,$j)
耗时增加:0.004101
内存增加:1411968
 
测试 $arr3[$n]=$n 
耗时增加:0.002527
内存增加:1411984
 
汇总
总耗时:0.008837
总内存:4235992
 
*/
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!