2

我试图检查 memory_get_peak_usage() 方法,我尝试在 for 循环中动态创建一个对象,并尝试打印我的 php 脚本使用的内存。这是代码:-

$objArr = array();
for( $i=1; $i<=100; $i++ ){
 echo "creating employee == " . memory_get_peak_usage()/1024 . " Kbs\n";
 $objArr[$i] = new CEmployee();
}
exit;

这是让我感到困惑的结果:-

creating employee == 4156.84375 Kbs
creating employee == 6619.640625 Kbs
creating employee == 6619.640625 Kbs
creating employee == 6619.640625 Kbs
...
...(up to 40 lines from 2nd line same result as above and then from 41 line changed)

creating employee == 6623.5546875 Kbs
creating employee == 6631.234375 Kbs
creating employee == 6638.9140625 Kbs
creating employee == 6646.59375 Kbs
creating employee == 6654.2734375 Kbs
creating employee == 6661.953125 Kbs
creating employee == 6669.6328125 Kbs
creating employee == 6677.3125 Kbs
creating employee == 6684.9921875 Kbs
....
....

我不知道 php 如何为对象分配内存。我在 Windows 7 的命令行界面上运行脚本

更新代码:-

gc_collect_cycles();
for( $i=1; $i<=100; $i++ ){
echo "creating employee == " . memory_get_usage()/1024 . " Kbs\n";
$objArr[$i] = new CEmployee();
    $objArr[$i]->setEmployeeNumber($i);
}exit;
4

1 回答 1

2

正如您所看到的,它确实增加了内存使用量:

http://codepad.org/RApsrlXh

但是,您可能已经准备好进行垃圾收集的数据,因此当您创建新数据时,CEmployee它可能正在使用该空间。

尝试gc_collect_cycles()在循环之前运行并使用memory_get_usage()以获得更准确的读数。

于 2012-08-30T08:09:50.650 回答