This article introduces how to use the memory_get_usage () function in php to obtain the current memory consumption and optimize the program performance. This article introduces how to use the memory_get_usage () function in php to obtain the current memory consumption and optimize the program performance.
Script ec (2); script
I. function prototype
Int memory_get_usage ([bool $ real_usage = false])
2. Version compatibility
PHP 4> = 4.3.2, PHP 5
III. Basic usage and Examples
1. Get the current memory consumption
| The Code is as follows: |
|
|
Echo memory_get_usage ();
$ Var = str_repeat ("liuhui", 10000 );
Echo memory_get_usage ();
Unset ($ var );
Echo memory_get_usage ();
?> |
Output: 62328 122504 62416
Note: The value output by the memory_get_usage () function is bytes.
2. format the memory_get_usage () output.
| The Code is as follows: |
|
|
Function convert ($ size ){
$ Unit = array ('B', 'kb', 'mb', 'gb', 'tb', 'petab ');
Return @ round ($ size/pow (1024, ($ I = floor (log ($ size, 1024), 2 ). ''. $ unit [$ I];
}
Echo convert (memory_get_usage (true ));
?> |
Output: 256 kb
3. the user-defined function obtains the array or variable value size.
| The Code is as follows: |
|
|
Function array_size ($ arr ){
Ob_start ();
Print_r ($ arr );
$ Mem = ob_get_contents ();
Ob_end_clean ();
$ Mem = preg_replace ("/n +/", "", $ mem );
$ Mem = strlen ($ mem );
Return $ mem;
}
$ MemEstimate = array_size ($ GLOBALS );
?> |