What is php memory usage

PHP Memory Leaks, How to Find and Fix Them

Memory leaks can happen in any language, including PHP. These memory leaks may happen in small increments that take time to accumulate, or in larger jumps that manifest quickly. Either way, if your app has a memory leak, sooner or later it will cause problems. The source of and solution to PHP memory leaks aren’t always obvious, so you may need to try a few strategies before you eliminate the problem.

PHP Memory Usage: How Memory Leaks Happen

What is a memory leak in PHP?

A memory leak in PHP is a condition that causes sections of code to continue using memory even though that memory is no longer needed. There are several ways for memory leaks to occur. Variables that never go out of scope, cyclical references, extensions in C that `malloc` instead of `emalloc` and for whatever reason don’t `free`, to name a few. There are surprising and quite subtle ways of using and holding on to memory in PHP. If enough memory is leaking, your application will eventually run into memory limits imposed by PHP settings or by the OS itself, and crash.

Читайте также:  Как сделать баннеры html

Does PHP have garbage collection?

Yes, PHP does have garbage collection that should help prevent memory leaks. However, several factors can prevent the garbage collector from fulfilling its task. For example, if an object’s refcount increases and never decreases, then the object is still technically in use and is not garbage. The garbage collector, therefore, cannot identify it as such and will not free up the object.

Garbage collection is active in PHP by default, but it can be disabled through settings in `php.ini`. If garbage collection is disabled, you’ll quickly accumulate unused memory that’s never freed. Disabling garbage collection can improve performance for scripts that are short-lived and completely exit (and therefore free all used memory), but for longer scripts and daemons you’ll probably want the garbage collector enabled.

How to Find PHP Memory Leaks

Identifying the source of your PHP memory leak is the first step to finding a solution. You can’t fix a problem until you understand its underlying cause.

Option One: Log Your Scripts

If you’re running multiple scripts, then you need to determine which one is causing the leak. Use `auto_append_file` and `memory_get*` to generate a log of your scripts. Then, review the scripts to see which ones use the most memory.

Option Two: Discover Peak Usage

Use `memory_get_peak_usage` to find out how much memory has been allocated to your script. If it looks abnormally high, then you might first look at your PHP script for code that may be unintentionally loading or iterating over more data than anticipated. If so, break down the loading or processing of the data into manageable chunks instead of all-at-once.

Читайте также:  Python set get one element

Option Three: Use a PHP Memory Profiler

Use the php-memprof extension to learn how much memory is still in use after a script runs.

Monitoring Memory Usage with a PHP Memory Profiler

Monitoring memory usage with a PHP memory profiler can make it much easier for you to spot problems within your scripts. Several PHP profilers include features that will detect memory leaks.

What is memory profiling?

Memory profiling scans your PHP scripts to see precisely how each function uses memory. The level of depth that you get will depend on the PHP memory profiler that you choose. Some, for example, will show you how much memory your functions use and continue use while running a script. Others will point you directly to problematic functions that cause PHP memory leaks and other performance issues.

Finding the right memory profiler is an essential part of debugging PHP scripts with memory leaks.

Xhprof PHP Memory Profiler

Xhprof has a simple user interface that will help you discover PHP memory leaks. It can also identify the performance issues that make PHP memory leaks happen.

Xdebug PHP Profiler

Xdebug is a standard PHP profiler that you can use to discover a variety of performance issues in your scripts. The lightweight profiler doesn’t use much memory, so you can run it alongside your PHP scripts for real-time performance debugging.

PHP-memprof

PHP-memprof is a stand-alone PHP memory profiler that can tell you exactly how much memory each of your functions uses. It can even trace an allocated byte back to a function.

Dig in!

It’s inevitable that at some point you’ll have to track down a memory issue with your PHP app. Unfortunately, memory leaks are the type of bug that can be notoriously difficult to hunt and fix. With the options covered here, we hope you have a good starting point to uncover and resolve any potential memory problems you encounter with your PHP application!

Follow Us on Social Media!

Источник

memory_get_usage

Returns the amount of memory, in bytes, that’s currently being allocated to your PHP script.

Parameters

Set this to true to get total memory allocated from system, including unused pages. If not set or false only the used memory is reported.

Note:

PHP does not track memory that is not allocated by emalloc()

Return Values

Returns the memory amount in bytes.

Examples

Example #1 A memory_get_usage() example

// This is only an example, the numbers below will
// differ depending on your system

echo memory_get_usage () . «\n» ; // 36640

$a = str_repeat ( «Hello» , 4242 );

echo memory_get_usage () . «\n» ; // 57960

echo memory_get_usage () . «\n» ; // 36744

See Also

User Contributed Notes 15 notes

To get the memory usage in KB or MB

function convert ( $size )
$unit =array( ‘b’ , ‘kb’ , ‘mb’ , ‘gb’ , ‘tb’ , ‘pb’ );
return @ round ( $size / pow ( 1024 ,( $i = floor ( log ( $size , 1024 )))), 2 ). ‘ ‘ . $unit [ $i ];
>

echo convert ( memory_get_usage ( true )); // 123 kb
?>

Note, that the official IEC-prefix for kilobyte, megabyte and so on are KiB, MiB, TiB and so on.

At first glance this may sound like «What the hell? Everybody knows, that we mean 1024 not 1000 and the difference is not too big, so what?». But in about 10 years, the size of harddisks (and files on them) reaches the petabyte-limit and then the difference between PB and PiB is magnificent.

Better to get used to it now. 🙂

memory_get_usage() is used to retrieve the memory allocated to PHP only (or your running script). But intuitively, many people expect to get the memory usage of the system, based on the name of the function.

So if you need the overall memory usage, following function might be helpful. If retrieves the memory usage either in percent (without the percent sign) or in bytes by returning an array with free and overall memory of your system. Tested with Windows (7) and Linux (on an Raspberry Pi 2):

// Returns used memory (either in percent (without percent sign) or free and overall in bytes)
function getServerMemoryUsage ( $getPercentage = true )
$memoryTotal = null ;
$memoryFree = null ;

if ( stristr ( PHP_OS , «win» )) // Get total physical memory (this is in bytes)
$cmd = «wmic ComputerSystem get TotalPhysicalMemory» ;
@ exec ( $cmd , $outputTotalPhysicalMemory );

// Get free physical memory (this is in kibibytes!)
$cmd = «wmic OS get FreePhysicalMemory» ;
@ exec ( $cmd , $outputFreePhysicalMemory );

// Find free value
foreach ( $outputFreePhysicalMemory as $line ) if ( $line && preg_match ( «/^1+\$/» , $line )) $memoryFree = $line ;
$memoryFree *= 1024 ; // convert from kibibytes to bytes
break;
>
>
>
>
else
if ( is_readable ( «/proc/meminfo» ))
$stats = @ file_get_contents ( «/proc/meminfo» );

if ( $stats !== false ) // Separate lines
$stats = str_replace (array( «\r\n» , «\n\r» , «\r» ), «\n» , $stats );
$stats = explode ( «\n» , $stats );

// Separate values and find correct lines for total and free mem
foreach ( $stats as $statLine ) $statLineData = explode ( «:» , trim ( $statLine ));

//
// Extract size (TODO: It seems that (at least) the two values for total and free memory have the unit «kB» always. Is this correct?
//

// Total memory
if ( count ( $statLineData ) == 2 && trim ( $statLineData [ 0 ]) == «MemTotal» ) $memoryTotal = trim ( $statLineData [ 1 ]);
$memoryTotal = explode ( » » , $memoryTotal );
$memoryTotal = $memoryTotal [ 0 ];
$memoryTotal *= 1024 ; // convert from kibibytes to bytes
>

// Free memory
if ( count ( $statLineData ) == 2 && trim ( $statLineData [ 0 ]) == «MemFree» ) $memoryFree = trim ( $statLineData [ 1 ]);
$memoryFree = explode ( » » , $memoryFree );
$memoryFree = $memoryFree [ 0 ];
$memoryFree *= 1024 ; // convert from kibibytes to bytes
>
>
>
>
>

if ( is_null ( $memoryTotal ) || is_null ( $memoryFree )) return null ;
> else if ( $getPercentage ) return ( 100 — ( $memoryFree * 100 / $memoryTotal ));
> else return array(
«total» => $memoryTotal ,
«free» => $memoryFree ,
);
>
>
>

function getNiceFileSize ( $bytes , $binaryPrefix = true ) if ( $binaryPrefix ) $unit =array( ‘B’ , ‘KiB’ , ‘MiB’ , ‘GiB’ , ‘TiB’ , ‘PiB’ );
if ( $bytes == 0 ) return ‘0 ‘ . $unit [ 0 ];
return @ round ( $bytes / pow ( 1024 ,( $i = floor ( log ( $bytes , 1024 )))), 2 ) . ‘ ‘ . (isset( $unit [ $i ]) ? $unit [ $i ] : ‘B’ );
> else $unit =array( ‘B’ , ‘KB’ , ‘MB’ , ‘GB’ , ‘TB’ , ‘PB’ );
if ( $bytes == 0 ) return ‘0 ‘ . $unit [ 0 ];
return @ round ( $bytes / pow ( 1000 ,( $i = floor ( log ( $bytes , 1000 )))), 2 ) . ‘ ‘ . (isset( $unit [ $i ]) ? $unit [ $i ] : ‘B’ );
>
>

// Memory usage: 4.55 GiB / 23.91 GiB (19.013557664178%)
$memUsage = getServerMemoryUsage ( false );
echo sprintf ( «Memory usage: %s / %s (%s%%)» ,
getNiceFileSize ( $memUsage [ «total» ] — $memUsage [ «free» ]),
getNiceFileSize ( $memUsage [ «total» ]),
getServerMemoryUsage ( true )
);

?>

The function getNiceFileSize() is not required. Just used to shorten size in bytes.

Источник

Время и память выполнения скрипта PHP

Несколько методов как узнать время генерации страницы и затраченный объем памяти PHP скрипта.

Время выполнения скрипта

Вариант 1

$start = microtime(true); . $time = microtime(true) - $start; echo $time . ' сек.';

Результат

Вариант 2

Вместо $start = microtime(true) брать значение из переменной $_SERVER[‘REQUEST_TIME_FLOAT’] , которая содержит время запроса к серверу.

. $time = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']; echo $time . ' сек.';

Вариант 3

Если на сервере установлен Xdebag.

. echo xdebug_time_index() . ' сек.';

Среднее время

Т.к. результат «скачет» и зависит от многих факторов (нагрузка на хостинг и т.д.), доработаем скрипт, добавив запись результата в лог и подсчет среднего арифметического значения.

$start = microtime(true); . $time = round(microtime(true) - $start, 3); $f = fopen('time.log', 'a'); fwrite($f, $time . PHP_EOL); fclose($f); $log = file('time.log'); $result = round(array_sum($log) / count($log), 3); echo $result . ' сек.';

Затраченная память

Функция memory_get_usage() – возвращает количество памяти в байтах, которое было выделено PHP-скрипту на данный момент.

В Xdebug есть функция xdebug_memory_usage() , которая возвращает тот же результат.

$memory = memory_get_usage(); . echo (memory_get_usage() - $memory) . ' байт';

Результат

Конвертация результата в килобайты и мегабайты

$memory = memory_get_usage(); . $memory = memory_get_usage() - $memory; $i = 0; while (floor($memory / 1024) > 0) < $i++; $memory /= 1024; >$name = array('байт', 'КБ', 'МБ'); echo round($memory, 2) . ' ' . $name[$i];

Результат

Время и память скрипта

Объединим приведенные методы в один скрипт.

$start = microtime(true); $memory = memory_get_usage(); . $memory = memory_get_usage() - $memory; $time = microtime(true) - $start; // Подсчет среднего времени. $f = fopen('time.log', 'a'); fwrite($f, $time . PHP_EOL); fclose($f); $log = file('time.log'); $time = round(array_sum($log) / count($log), 3); // Перевод в КБ, МБ. $i = 0; while (floor($memory / 1024) > 0) < $i++; $memory /= 1024; >$name = array('байт', 'КБ', 'МБ'); $memory = round($memory, 2) . ' ' . $name[$i]; echo $time . ' сек. / ' . $memory;

Источник

Оцените статью