我正在为我的分析代码编写单元测试。为此,我正在编写一些函数来分配内存并调用“睡眠”,以便生成可预测的内存和时间结果以供测试。
“分配内存”部分有点棘手。
如果没有“malloc”类型函数,我尝试附加到字符串: $myString .= 'x'; 并附加到数组: $myArray[] = null;
但我的结果表明这些结构不会按需线性分配内存。
感谢您的建议!
PHP 是一种高级语言。内存管理由引擎决定。您不能也不应该尝试解决此问题。
而是分析那些在 PHP 中实际上有用的东西,比如现实生活中字符串和数组的使用。
这是一个测试函数,它将内存分块分配到一系列数组中,直到总内存限制耗尽。也许您也可以使用类似的方法来根据需要分配内存。有点像 malloc() C 函数。
在我的网络服务器上,我得到以下结果:
Memory Test
Memory Limit: 536870912
Initial memory usage: 637448
Allocate 1 million single character elements to myArray0
Current memory usage: 97026784
Allocate 1 million single character elements to myArray1
Current memory usage: 193415768
Allocate 1 million single character elements to myArray2
Current memory usage: 289804704
Allocate 1 million single character elements to myArray3
Current memory usage: 386193640
Allocate 1 million single character elements to myArray4
Current memory usage: 482582576
Memory Test Complete
Total memory used: 482582576
Average memory used per array in each of 5 arrays: 96389025
Average memory used per character in each of 5 arrays: 96
Remaining memory: 54288336
// This routine demonstrates how to get and use PHP memory_limit, memory_get_usage, variable array names, and array_fill
// to allocate large blocks of memory without exceeding php.ini total available memory
echo "<h2>Memory Test</h2>";
// Get total memory available to script
$memory_limit = get_memory_limit();
echo "Memory Limit: $memory_limit <br />";
$initMemory = $currentMemory = memory_get_usage();
echo "Initial memory usage: $initMemory <br /><br />";
// Start consuming memory by stuffing multiple arrays with an arbitrary character
$i =0;
while ( $currentMemory + ($currentMemory - $initMemory)/($i+1) <= $memory_limit)
{
echo "Allocate 1 million single character elements to myArray$i <br />";
${myArray.$i} = array_fill(0, 1000000, "z");
$currentMemory = memory_get_usage();
echo "Current memory usage: $currentMemory <br />";
$i++;
}
echo "<h2>Memory Test Complete</h2>";
echo "Total memory used: $currentMemory <br />";
$aveMemoryPerArray = (int)(($currentMemory - $initMemory)/$i);
echo "Average memory used per array in each of " .$i . " arrays: " . $aveMemoryPerArray . " <br />";
echo "Average memory used per character in each of " . $i . " arrays: " . (int)($aveMemoryPerArray/1000000) . " <br />";
echo "Remaning memory: " . ($memory_limit - $currentMemory) . "<br />";
// Utility to convert php.ini memory_limit text string into an integer value in bytes
// Reference: http://stackoverflow.com/questions/10208698/checking-memory-limit-in-php
function get_memory_limit()
{
$memory_limit = ini_get('memory_limit');
if (preg_match('/^(\d+)(.)$/', $memory_limit, $matches)) {
if ($matches[2] == 'M') {
$memory_limit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
} else if ($matches[2] == 'K') {
$memory_limit = $matches[1] * 1024; // nnnK -> nnn KB
}
}
return $memory_limit;
}