想粗略地理解一個腳本消耗了多少內存,或著在你往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-MemoryUsageMemory usage: 6.7 MB (6,990,328 Bytes)PS> $array = 1..100000PS> Get-MemoryUsageMemory usage: 10.2 MB (10,700,064 Bytes, +3709736)PS> Remove-Variable -Name arrayPS> Get-MemoryUsageMemory usage: 7.4 MB (7,792,424 Bytes, -2907640)
新聞熱點
疑難解答