c# - 测量进程内存使用给出极低(错误)的值

标签 c# performance .net-4.0

我有以下代码来启动和监控进程:

Process process = new Process();
process.StartInfo.FileName = "foo.exe";

long maxMemoryUsage = 0;

process.Start()

while(!process.HasExited)
{
    maxMemoryUsage = Math.Max(maxMemoryUsage, process.PrivateMemorySize64);
}

在使用此代码运行一个大型应用程序后,根据任务管理器,该应用程序在其峰值时使用了 328 MB(内存“私有(private)工作集”)。 maxMemoryUsage 的值和 process.PeakPagedMemorySize64 的值是 364544。根据 MSDN该值应解释为字节,这意味着它略高于 300KB,与预期值相差千分之一。另一个 process.Peak...Memory 属性也报告了极低的值(都低于 1 兆字节,除了 PeakVirtualMemorySize64 是 4MB,我认为这是该字段的最小值)。

我已经尝试启动不同的应用程序(C# 和 C++ 基于它们我有源代码),我知道它们使用很少或很多内存,并且内存值总是非常接近这个过程中看到的值.显然我在做一些完全错误的事情。

所以我的问题是:如何测量从 C# 应用程序生成的进程的最大内存使用量。 (请注意,只要程序退出后我知道它的值,我就不需要 ealtime 的值,我也不需要它非常精确,因为我不在乎它是 27.04MB 还是 30MB,但我请注意它是 30MB 还是 100MB)。

编辑:这里是一个完整的可重现的测试用例

class Program
{
    static void Main(string[] args)
    {
        Process process = new Process();
        process.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\devenv.exe";

        long maxMemoryUsage = 0;

        process.Start();

        while(!process.HasExited)
        {
            maxMemoryUsage = Math.Max(maxMemoryUsage, process.PagedMemorySize64);
        }

        Console.Out.WriteLine("Memory used: " + (maxMemoryUsage / 1024.0) / 1024.0 + "MB");

        Console.ReadLine();
    }
}

根据任务管理器,Visual Studio 使用 103MB。关闭 Visual Studio 后,程序报告 0.3984375MB。

最佳答案

进程类被大量缓存。无论您读取某个属性多少次,除非您调用 Refresh 方法,否则您只会获得缓存的结果。您需要调用Process.Refresh获取非缓存结果。

引用自msdn

When a Process component is associated with a process resource, the property values of the Process are immediately populated according to the status of the associated process. If the information about the associated process subsequently changes, those changes are not reflected in the Process component's cached values. The Process component is a snapshot of the process resource at the time they are associated. To view the current values for the associated process, call the Refresh method.

因此,您的代码将变为:

while(!process.HasExited)
{
    process.Refresh();
    maxMemoryUsage = Math.Max(maxMemoryUsage, process.PrivateMemorySize64);
}

您也可以考虑查看 process.PeakXXX 属性,我想这会对您有所帮助。

关于c# - 测量进程内存使用给出极低(错误)的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25220202/

相关文章:

c# - 如何从/bin 目录中加载所有程序集

c# - 如何摆脱异常 "The ' Microsoft.ACE.OLEDB.12。 Win 7 中的 0' provider is not registered on the local machine"

c# - 自动将接口(interface)注册到 autofac 中的类

c++ - 非托管 C++ COM 和托管 C++ .NET4 互操作

c# - 反序列化具有抽象类型属性的对象

performance - 如何为一般情况编写伪代码?

PHP:哪个更有效:连接的返回变量,还是单独返回每一行?

iphone - 在 UIView 中逐步绘制 (iPhone)

c# - 将 MemoryStream 的内容作为 ASCII 字符串获取的快速方法

c# - 异常 : An expression tree may not contain a dynamic operation