百科狗-知识改变命运!
--

memory_get_usage() - php 选项信息函数

百变鹏仔1年前 (2023-11-21)阅读数 22#技术干货
文章标签存量

memory_get_usage()

(PHP 4 >= 4.3.2, PHP 5, PHP 7)

返回分配给 PHP 的内存量

说明

memory_get_usage([bool $real_usage= false]): int

memory_get_usage() - php 选项信息函数

返回当前分配给你的 PHP 脚本的内存量,单位是字节(byte)。

参数

$real_usage

如果设置为TRUE,获取系统分配总的内存尺寸,包括未使用的页。如果未设置或者设置为FALSE,仅仅报告实际使用的内存量。

Note:

PHP 不跟踪非emalloc()分配的内存

返回值

返回内存量字节数。

更新日志

版本说明
5.2.1不需要在编译时使用--enable-memory-limit选项就能够使用这个函数。
5.2.0增加了参数$real_usage。

范例

一个memory_get_usage()例子

参见

  • memory_get_peak_usage() 返回分配给 PHP 内存的峰值
  • memory_limit
To get the memory usage in KB or MB 
memory_get_usage() is used to retrieve the memory allocated to PHP only (or your running script). But intuitively, many people expect to get the memory usage of the system, based on the name of the function.
So if you need the overall memory usage, following function might be helpful. If retrieves the memory usage either in percent (without the percent sign) or in bytes by returning an array with free and overall memory of your system. Tested with Windows (7) and Linux (on an Raspberry Pi 2):

True, it's not much of a performance boost, but every bit helps.
I can confirm that this function triggers a garbage collection. I have a script that exceeded 128MB of memory at some point and ended with a fatal error. I was confused, because the script dealt with some large files initially, but the memory load from that point on should have been marginal, and the error occurred at the very end.
Those large files were dealt in a dedicated function and i even used unset() on the variable holding the file after the file was written to disk inside that function. So the memory should have been cleared twice, first after the unset() call, and second once the function ended.
To debug the memory usage, I called memory_get_usage(true) at some points and echo-ed the memory allocation. Just by adding a few echos here and there in the script, the memory usage never exceeded 1MB overhead (on top of the current file size) and the memory error disappeared.
The method sandeepc at myrealbox dot com posted yields larger memory usage, my guess is that it includes all the PHP interpreter/internal code and not just the script being run.
1) Use ps command
MEMORY USAGE (% KB PID ): 0.8 12588 25087 -> about 12MB
2) Use memory_get_usage() 
int(6041952) -> about 6MB
This is a function that should work for both Windows XP/2003 and most distrabutions of UNIX and Mac OS X. 
内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)