【发布时间】:2017-10-26 00:27:35
【问题描述】:
我有一个从 cron 任务运行的 PHP 脚本。我是这样的
<?php
require_once 'script1.php';
// Here I do a lot of SQL querys, and my memory usage and allocated memory goes up
// then I set all the variables to null and unset them to free memory
gc_collect_cycles(); // I added this to try to force freeing memory
require_once 'script2.php';
// Here I do a lot of SQL querys, and my allocated memory goes up again ...
gc_collect_cycles(); // I added this to try to force freeing memory
require_once 'script3.php';
// And Here when I do one big query it throws me the 'Allowed memory size' error.
这些是内存的转储,用......制作的。
MEM=memory_get_usage(false)
MEMR=memory_get_usage(true)
MEMpeak=memory_get_peak_usage(false)
MEMRpeak=memory_get_peak_usage(true)
1) 在脚本 1 之后:
MEM 5.9628219604492 MEMR 244 MEMpeak 243.41315460205 MEMRpeak 248.5
2) 在脚本 2 之后:
MEM 7.9203491210938 MEMR 244 MEMpeak 243.41315460205 MEMRpeak 251.34765625`
3) 在脚本 3 之前:
MEM 7.8667755126953 MEMR 244 MEMpeak 243.41315460205 MEMRpeak 251.34765625
4) 在脚本 3 上,在我执行 'mysqli_query(...':
之前的行MEM 9.0010223388672 MEMR 244 MEMpeak 243.419090271 MEMRpeak 251.34765625
然后我得到错误:
PHP 致命错误:Allowed memory size of 268435456 bytes exhausted (tried to allocate 19552176 bytes) in ...
但是,如果我将内存限制增加到 512M,我会在之前崩溃的行之后得到这个内存转储:
MEM 35.54125213623 MEMR 266.6484375 MEMpeak 243.419090271 MEMRpeak 266.6484375
我不明白发生了什么:在脚本 3 的请求中,我有 243MB 的已分配内存和 9MB 已用内存(所以我还有 234MB 的空闲分配内存,对吧?)。
然后 PHP 尝试多分配 22MB 的内存(必须在内存上多保存 29MB 的数据)。
为什么不使用空闲分配的内存?
编辑:这些是我单独运行脚本 3 时的读数:
-
开始:
MEM 5.83447265625 MEMR 8 MEMpeak 6.7176361083984 MEMRpeak 8 -
结束(在将所有变量设置为 null 之前):
MEM 57.858413696289 MEMR 90.25 MEMpeak 107.6799621582 MEMRpeak 108.8984375 -
结束(将所有变量设置为 null 之后):
MEM 6.9840774536133 MEMR 88 MEMpeak 107.6799621582 MEMRpeak 108.8984375
【问题讨论】:
标签: php memory memory-management memory-leaks php-7