To test the memory and time consumed by code execution in php, we can directly use the two functions, microtime and memory_get_usage. I will introduce them to you.
Let's take a look at the usage of the microtime and memory_get_usage functions.
Meaning and usage
Microtime ()The function returns the current Unix Timestamp and the number of microseconds.
Syntax
Microtime (get_as_float) parameter description
If the get_as_float parameter is given and its value is equivalent to TRUE, this function returns a floating point number.
Example
The Code is as follows: |
Copy code |
<? Php Echo (microtime ()); ?> |
Output:
0.25139300 1138197510
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: |
Copy code |
<? Php Echo memory_get_usage (); $ Var = str_repeat (www. bKjia. c0m, 10000 ); Echo memory_get_usage (); Unset ($ var ); Echo memory_get_usage (); ?> |
Result: 62328 122504 62416
Note: The value output by the memory_get_usage () function is bytes.
2. The result of formatting memory_get_usage () is output in KB.
The Code is as follows: |
Copy code |
<? Php 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 )); ?> |
265KB
Now we have finished introducing the two functions. Let's take a look at a test instance.
The Code is as follows: |
Copy code |
<? Php $ T1 = microtime (true ); $ M1 = memory_get_usage (true ); Echo fixByte ($ m1). '<br/> '; /* When there are too many threads, there are too many threads, too many threads */ /* When there are too many threads, there are too many threads, too many threads */ $ T2 = microtime (true ); $ M2 = memory_get_usage (true ); Echo '<br/>'. fixByte ($ m2). '<br/> '; Echo 'Echo 'time'. round ($ t2-$ t1), 4). '<br/> '; Echo 'mem '. fixByte ($ m2-$ m1).' <br/> '; /** * Format the byte as a proper value. * @ Param int $ byte bytes * @ Param string $ string the number of readable bytes formatted */ Function fixByte ($ byte, $ string = true, $ dot_num = 9 ){ $ Ret = array ( 'Data' => $ byte, 'Danwei' => 'byte ', ); If ($ byte <1024 ){ } Else if ($ byte <1024*1024 ){ $ Ret ['data'] = round ($ byte/1024, $ dot_num ); $ Ret ['danwei'] = 'K '; } Else if ($ byte <1024*1024*1024 ){ $ Ret ['data'] = round ($ byte/(1024*1024), $ dot_num ); $ Ret ['danwei'] = 'M '; } Else if ($ byte <1024*1024*1024*1024 ){ $ Ret ['data'] = round ($ byte/(1024*1024*1024), $ dot_num ); $ Ret ['danwei'] = 'gb '; } Else if ($ byte <1024*1024*1024*1024*1024 ){ $ Ret ['data'] = round ($ byte/(1024*1024*1024*1024), $ dot_num ); $ Ret ['danwei'] = 'tb '; } If ($ string ){ $ Ret = $ ret ['data']. ''. $ ret ['danwei']; } Return $ ret; } |