在Powershell中获取对象的内存大小

问题描述 投票:0回答:3

我有一个(长时间运行的)脚本正在尝试执行。不幸的是,当它运行时,powershell 的内存使用量开始逐渐增加。脚本比较简单,看不出有什么明显的内存泄漏。然而,我使用的 API 可能表现不佳。

有没有一种简单的方法可以从 powershell 中获取对象的内存大小,以便我可以查看我的怀疑是否正确?

powershell memory-leaks
3个回答
9
投票

也许一个粗略的做法是这样的:

$memBefore = (Get-Process -id $pid).WS
# Create object here...
$memAfter = (Get-Process -id $pid).WS
($memAfter - $memBefore) / 1KB

如果是内存泄漏,您可以通过以下方式缓解:

[gc]::Collect()

6
投票

另一种近似方法:

$before = [gc]::GetTotalMemory($true)
$s = "A new string object"
$after = [gc]::GetTotalMemory($true)

($after - $before)/1kb # return the delta in KBytes

0
投票

这看起来不错,来自 reddit。至少对于简单类型来说是这样。

using namespace System.Runtime.InteropServices
$tmp = 1234567890 # int32
[Marshal]::SizeOf($tmp)

4


$tmp = 12345678900 # int64
[Marshal]::SizeOf($tmp)

8


$tmp = 12345678900000000000 # decimal
[Marshal]::SizeOf($tmp)

16
© www.soinside.com 2019 - 2024. All rights reserved.