w3resource

PHP Math Exercises: Get the information regarding memory usage in KB or MB


6. Get Memory Usage Information

Write a PHP script to get the information regarding memory usage in KB or MB etc.

Visual Presentation:

PHP Math Exercises: Get the information regarding memory usage in KB or MB

Sample Solution:

PHP Code:

<?php
$memory_size = memory_get_usage(); // Get the memory usage of the script and store it in $memory_size
$memory_unit = array('Bytes','KB','MB','GB','TB','PB'); // Define an array containing memory size units

// Display memory size into kb, mb etc.
echo 'Used Memory : '.round($memory_size/pow(1024,($x=floor(log($memory_size,1024)))),2).' '.$memory_unit[$x]."\n";
?>

Output:

Used Memory : 342.57 KB 

Explanation:

In the exercise above,

  • $memory_size = memory_get_usage();: This line retrieves the current memory usage of the PHP script and stores it in the variable '$memory_size'.
  • $memory_unit = array('Bytes','KB','MB','GB','TB','PB');: This line initializes an array '$memory_unit' with memory size units ('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB'). These units will represent the memory size in a human-readable format.
  • echo 'Used Memory : '.round($memory_size/pow(1024,($x=floor(log($memory_size,1024)))),2).' '.$memory_unit[$x]."\n";: This line calculates the memory size in the appropriate unit (KB, MB, etc.) and prints it along with the corresponding unit. It uses logarithmic calculations to determine the appropriate unit based on the size of '$memory_size'. Finally, it appends a newline character ("\n") to the output.

Flowchart :

Flowchart: Get the information regarding memory usage in KB or MB

For more Practice: Solve these Related Problems:

  • Write a PHP script to retrieve the current memory usage in bytes and convert it to KB or MB as appropriate, then output the formatted result.
  • Write a PHP function that monitors memory usage before and after executing a block of code and displays the difference in human-readable format.
  • Write a PHP program to log the memory usage details of a script execution into a file with timestamps and formatted units.
  • Write a PHP script to compare memory consumption of two different operations and output the results with appropriate unit conversion.

Go to:


PREV : Convert Date Format from yyyy-mm-dd to dd-mm-yyyy.
NEXT : Find Earliest and Latest Dates.

PHP Code Editor:



Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.