Memory_get_usage get the current PHP memory consumption example

Source: Internet
Author: User
    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. ?>
Copy Code

Output: 62328 122504 62416 Description: The Memory_get_usage () function outputs a value of bytes units

2, Format memory_get_usage () output

    1. function Convert ($size) {
    2. $unit =array (' B ', ' KB ', ' MB ', ' GB ', ' TB ', ' PB ');
    3. Return @round ($size/pow (1024x768, ($i =floor (log ($size, 1024))), 2). ' '. $unit [$i];
    4. }
    5. echo Convert (Memory_get_usage (true));
    6. ?>
Copy Code

Output: KB

3, Custom function get 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. ?>
Copy Code

Note: To reduce memory usage, you can use the PHP unset () function to remove variables that you no longer need to use. Similar functions: The PHP mysql_free_result () function, which empties the resulting set of query databases that are no longer needed, can also get more usable memory.

PHP Memory_get_usage () can also have a parameter, $real _usage, whose value is a Boolean value. The default is FALSE, which indicates that the resulting memory usage does not include the memory used by the function (PHP memory manager), and when set to TRUE, the resulting memory is included in the memory used by the function (PHP memory manager).

In PHP programming, you can use PHP memory_get_usage () to compare the various methods used to occupy memory, and then choose a better method.

  • 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.