Memory_get_usage example of getting the current PHP memory consumption-php Tutorial

Source: Internet
Author: User
Memory_get_usage: an example of getting the current PHP memory consumption

  1. Echo memory_get_usage ();
  2. $ Var = str_repeat ("phpzixue.cn", 10000 );
  3. Echo memory_get_usage ();
  4. Unset ($ var );
  5. Echo memory_get_usage ();
  6. ?>

Output: 62328 122504 62416 description: the output value of the memory_get_usage () function is bytes.

2. format the memory_get_usage () output.

  1. Function convert ($ size ){
  2. $ Unit = array ('B', 'KB', 'mb', 'GB', 'TB', 'petab ');
  3. Return @ round ($ size/pow (1024, ($ I = floor (log ($ size, 1024), 2 ). ''. $ unit [$ I];
  4. }
  5. Echo convert (memory_get_usage (true ));
  6. ?>

Output: 256 kb

3. the user-defined function obtains the array or variable value size.

  1. Function array_size ($ arr ){
  2. Ob_start ();
  3. Print_r ($ arr );
  4. $ Mem = ob_get_contents ();
  5. Ob_end_clean ();
  6. $ Mem = preg_replace ("/\ n +/", "", $ mem );
  7. $ Mem = strlen ($ mem );
  8. Return $ mem;
  9. }
  10. $ MemEstimate = array_size ($ GLOBALS );
  11. ?>

Note: to reduce memory usage, you can use the PHP unset () function to delete unnecessary variables. Similar to the function: PHP mysql_free_result (), you can clear the result set of a database query that is no longer needed, so that more available memory can be obtained.

PHP memory_get_usage () can also have a parameter $ real_usage with a Boolean value. The default value is FALSE, indicating that the obtained memory usage does not include the memory occupied by this function (PHP memory manager). when it is set to TRUE, the obtained memory includes this function (PHP memory manager) memory used.

In php programming, you can use PHP memory_get_usage () to compare the memory usage of each method, and then select a method with better performance.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.