此函数传递大约70k个对象进行处理。加载数组没有问题,它在失败前经历了大约一半的迭代。内存仅限于ini_set('memory_limit','465M');
(云服务)。它始终在$googleFunction
:/app/vendor/googleads/googleads-php-lib/src/Google/Api/Ads/Common/Lib/AdsSoapClient.php
中失败。
我已经尝试将数组作为参考传递,一次从array_chunk
切换为使用array_slice
,并通过引用将$chunk
传递给$googleFunction
,在最后取消设置$chunk
,并在每次迭代后调用gc_collect_cycles()
。
怎么还会失败?某处必须存在内存泄漏,但除了$chunk
和$result
之外没有大的赋值,并且每次迭代期间调用的每个函数都超出范围,因此它可能分配的任何内容都应该是垃圾收集。我觉得它可能与函数引用有关。大约四分之一的迭代后,它使用240M。它每次迭代增长约10M。
function googleJob($job = null, &$list, $googleFunction, $before = null) {
// initialize $total, $gaw, $processed
for ($chunkIndex = 0; $chunkIndex < count($list); $chunkIndex += 2000) {
echo '3:'.memory_get_usage().' ';
$chunk = array_slice($list, $chunkIndex, 2000); # limit of 2000/request
echo '4:'.memory_get_usage().' ';
if ($before) {
foreach ($chunk as $item) {
$before($item); # function reference
}
}
echo '5:'.memory_get_usage().' ';
$i = 0; // try harder to make Google work
$result = null;
do {
try {
$result = $gaw->$googleFunction($chunk);
echo '6:'.memory_get_usage().' ';
} catch (\SoapFault $e) { # try to remove the bad items and try again
// no errors generated
}
} while ($result == null && $chunk); // Retry the request if not empty
array_walk($chunk, function($item) { $item->save(); });
echo '7:'.memory_get_usage().' ';
$processed += count($chunk);
if ($job) {
$job->progress = round($processed / $total * 100);
$job->save() or Yii::error($job->getErrors());
}
echo '8:'.memory_get_usage().' ';
unset($chunk);
unset($result);
echo '9:'.memory_get_usage().'... ';
gc_collect_cycles();
echo memory_get_usage().PHP_EOL;
}
}
内存'分析'输出:
3:110267832 4:110372112 5:111920328 6:123908368 7:129432080 8:129432080 9:121662520... 121662520
3:121662520 4:121766800 5:123281704 6:138001000 7:143493888 8:143493888 9:135745264... 135745264