当前位置: 代码网 > it编程>前端脚本>Powershell > PowerShell实现动态获取当前脚本运行时消耗的内存

PowerShell实现动态获取当前脚本运行时消耗的内存

2024年05月18日 Powershell 我要评论
想粗略地理解一个脚本消耗了多少内存,或着在你往powershell中的变量存结果时,消耗了多少内存,可以借助于下面的函数:#requires -version 2 $script:last_memor

想粗略地理解一个脚本消耗了多少内存,或着在你往powershell中的变量存结果时,消耗了多少内存,可以借助于下面的函数:

#requires -version 2
 
$script:last_memory_usage_byte = 0
 
function get-memoryusage
{
$memusagebyte = [system.gc]::gettotalmemory('forcefullcollection')
$memusagemb = $memusagebyte / 1mb
$diffbytes = $memusagebyte - $script:last_memory_usage_byte
$difftext = ''
$sign = ''
if ( $script:last_memory_usage_byte -ne 0 )
{
if ( $diffbytes -ge 0 )
{
$sign = '+'
}
$difftext = ", $sign$diffbytes"
}
write-host -object ('memory usage: {0:n1} mb ({1:n0} bytes{2})' -f $memusagemb,$memusagebyte, $difftext)
 
# save last value in script global variable
$script:last_memory_usage_byte = $memusagebyte
}


你可以在任何时候运行get-memoryusage,它会返回当前脚本最后一次调用后消耗的内存,同时和你上一次调用get-memoryusage运行结果的进行对比,并显示内存的增量。

这里的关键点是使用了gc,它在.net framwwork中负责垃圾回收,通常不会立即释放内存,想要粗略地计算内存消耗,垃圾回收器需要被指定释放未被使用的内存[gc]::collect(),然后再统计分配的内存。

为了更好的演示上面的函数我们来看一个调用的例子:

ps> get-memoryusage
memory usage: 6.7 mb (6,990,328 bytes)
ps> $array = 1..100000
ps> get-memoryusage
memory usage: 10.2 mb (10,700,064 bytes, +3709736)
ps> remove-variable -name array
ps> get-memoryusage
memory usage: 7.4 mb (7,792,424 bytes, -2907640)


(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com