w3resource

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

PHP math: Exercise-6 with Solution

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

PHP Code Editor:

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

Previous: Write a PHP script to convert a date from yyyy-mm-dd to dd-mm-yyyy.
Next: Find earliest and latest dates from a list of dates.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-math-exercise-6.php