萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> 編程語言綜合 >> PowerShell實現動態獲取當前腳本運行時消耗的內存

PowerShell實現動態獲取當前腳本運行時消耗的內存

   這篇文章主要介紹了PowerShell實現動態獲取當前腳本運行時消耗的內存,本文直接給出實現腳本函數,需要的朋友可以參考下

  想粗略地理解一個腳本消耗了多少內存,或著在你往PowerShell中的變量存結果時,消耗了多少內存,可以借助於下面的函數:

  ?

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 #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(),然後再統計分配的內存。

  為了更好的演示上面的函數我們來看一個調用的例子:

  ?

1 2 3 4 5 6 7 8 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)
copyright © 萬盛學電腦網 all rights reserved