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.
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.