如何找到方法分配的内存量?
我想知道方法运行时分配的内存总量。到目前为止,我已经:
GC.Collect()
GC.WaitForPendingFinalizers()
memStart = GC.GetTotalMemory(false)
f()
memEnd = GC.GetTotalMemory(false)
print (memEnd - memStart)
这对于简单的函数来说似乎工作得足够好,但是当 f
分配太多以至于强制收集时,结果会排除已经收集的对象。不仅如此,还没有办法知道这个“溢出”发生了。
有没有简单的方法可以做到这一点?无需购买/安装/配置内存分析器?像分配器/收集器的秒表这样的东西是理想的。所以我可以这样做:
sw = new GCStopwatch()
sw.Start()
f()
sw.Stop()
print sw.TotalBytesAllocated
print sw.NumberOfCollections
// etc
我想要这个,这样我就可以找出一个方法给垃圾收集器带来了多大的压力。我的代码使用沿着 Int32.Parse(s.Substring(4,6))
的大量调用从固定长度的字符串中读取数字,并且我考虑通过引入 < code>ParseInt(String s, int startIndex, int length) 以避免分配数万个子字符串。但这在其他场景中也是一个很好的工具。
I'd like to know the total amount of memory allocated while a method runs. So far I have:
GC.Collect()
GC.WaitForPendingFinalizers()
memStart = GC.GetTotalMemory(false)
f()
memEnd = GC.GetTotalMemory(false)
print (memEnd - memStart)
This seems to work well enough for simple functions but when f
allocates so much that it forces a collection then the result excludes the already collected objects. Not only that, there is no way of telling that this "overflow" happened.
Is there an easy way to do this? Without buying/installing/configuring a memory profiler? Something like a Stopwatch for the allocator/collector would be ideal. So I could do:
sw = new GCStopwatch()
sw.Start()
f()
sw.Stop()
print sw.TotalBytesAllocated
print sw.NumberOfCollections
// etc
I want this so I can find out how much pressure a method is putting on the garbage collector. My code is reading numbers from a fixed length string using lots of calls along the lines of Int32.Parse(s.Substring(4,6))
and I considered doing the parsing in-place by introducing ParseInt(String s, int startIndex, int length)
to avoid allocating tens of thousands of substrings. But this would be a nice tool to have in other scenarios too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我一直使用性能计数器进行此类分析。不完美但通常足够好。
这两行不会等待垃圾收集器实际完成。无论如何,在函数调用期间可能会发生垃圾收集。最好只衡量性能/时间作为优化。
I've always used performance counters for these kind of analysis. Not perfect but usually good enough.
Those two lines won't wait for the Garbage collector to actually finish. And a garbage collection might occur during you're function call anyway. It might be better to just measure performance/time as an optimisation.
我知道您说过您不想使用内存分析器,但这正是一种有用的情况。只需下载类似 ANTS Memory Profiler,并使用 14 天免费试用。它应该可以让您立即了解正在发生的事情。
I know you said that you don't want to use a memory profiler, but this is exactly the sort of situation that one is useful in. Just download something like ANTS Memory Profiler, and use the 14 day free trial. It should give you a fairly instant picture of what's going on.