PowerShell实现动态获取当前脚本运行时消耗的内存
2019/7/10 21:22:49
本文主要是介绍PowerShell实现动态获取当前脚本运行时消耗的内存,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
想粗略地理解一个脚本消耗了多少内存,或着在你往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)
这篇关于PowerShell实现动态获取当前脚本运行时消耗的内存的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2022-09-14SharePoint 2019 用 PowerShell将启用发布功能站点网站集另存为模板
- 2022-08-30PowerShell教程 - 程序性能和BUG分析工具
- 2022-08-30PowerShell教程 - 模块管理(Modules Management)
- 2022-08-29PowerShell教程 - Web requests(Web请求)
- 2022-08-26PowerShell教程 - 日期时间管理(Date & Time Management)
- 2022-08-25PowerShell教程 - 磁盘与硬件管理(Disk & Hardware Management)
- 2022-08-25PowerShell教程 - 系统事件管理(System Event Management)
- 2022-08-25PowerShell教程 - 文件系统管理(File System Management)
- 2022-08-24PowerShell教程 - 网络管理(Network Management)
- 2022-08-24PowerShell