PowerShell implementation dynamically gets the memory consumed by the current script runtime _powershell

Source: Internet
Author: User
Tags garbage collection memory usage

To get a rough idea of how much memory a script consumes, or how much memory is consumed when you save a result to a variable in PowerShell, you can use the following function:

#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)
 
# SA ve last value in script global variable
$script: last_memory_usage_byte = $memusagebyte
}


You can run get-memoryusage at any time, and it will return the memory consumed by the last invocation of the current script, in contrast to the results of your last call to Get-memoryusage, and display the increment of memory.

The key point here is to use GC, which is responsible for garbage collection in. NET framwwork, usually does not immediately release memory, want to calculate the memory consumption roughly, the garbage collector needs to be specified to free unused memory [Gc]::collect (), and then statistics the allocated memory.

To better demonstrate the above function, let's look at an example of an invocation:

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)


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.