memory_get_peak_usage() with “real usage”

后端 未结 5 1071
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 08:16

If the real_usage argument is set to true the PHP DOCS say it will get the real size of memory allocated from system. If it\'s false

5条回答
  •  悲哀的现实
    2020-12-02 08:40

    Ok, lets test this using a simple script:

    ini_set('memory_limit', '1M');
    $x = '';
    while(true) {
      echo "not real: ".(memory_get_peak_usage(false)/1024/1024)." MiB\n";
      echo "real: ".(memory_get_peak_usage(true)/1024/1024)." MiB\n\n";
      $x .= str_repeat(' ', 1024*25); //store 25kb more to string
    }
    

    Output:

    not real: 0.73469543457031 MiB
    real: 0.75 MiB
    
    not real: 0.75910949707031 MiB
    real: 1 MiB
    
    ...
    
    not real: 0.95442199707031 MiB
    real: 1 MiB
    
    not real: 0.97883605957031 MiB
    real: 1 MiB
    
    PHP Fatal error:  Allowed memory size of 1048576 bytes exhausted (tried to allocate 793601 bytes) in /home/niko/test.php on line 7
    

    Seems like real usage is the memory allocated from the system - which seems to get allocated in larger buckets than currently needed by the script. (I guess for performance reasons). This is also the memory the php process uses.

    The $real_usage = false usage is the memory usage you actually used in your script, not the actual amount of memory allocated by Zend's memory manager.

    Read this question for more information.

    In short: to get how close are you to the memory limit, use $real_usage = true

提交回复
热议问题