【问题标题】:How can I time how long garbage collection is taking in C#? [closed]如何计算 C# 中垃圾收集的时间? [关闭]
【发布时间】:2015-05-06 12:52:07
【问题描述】:

我想计算垃圾收集需要多长时间。

根据这些文章:

我想出了下面的代码。这是在 C# 中计算垃圾收集时间的正确方法吗?

class Program
{
    public static void Main(string[] args)
    {
        var done = false;
        var load = new List<byte[]>();

        var pollGC = new Action(() =>
        {
            // Register for a notification. 
            GC.RegisterForFullGCNotification(10, 10);
            Console.WriteLine("Registered for GC notification.");

            Stopwatch gcTimer = new Stopwatch();

            while (!done)
            {
                // Check for a notification of an approaching collection.
                GCNotificationStatus s = GC.WaitForFullGCApproach();
                if (s == GCNotificationStatus.Succeeded)
                {
                    Console.WriteLine("GC is about to start.");
                    load.Clear();
                    gcTimer.Restart();
                }

                // Check for a notification of a completed collection.
                s = GC.WaitForFullGCComplete();
                if (s == GCNotificationStatus.Succeeded)
                {
                    Console.WriteLine("GC has finished in {0} ms", gcTimer.ElapsedMilliseconds);
                }

                Thread.Sleep(500);
            }
            GC.CancelFullGCNotification();

            Console.WriteLine("Finished monitoring GC");

        });

        var doWork = new Action(() =>
        {
            while (!done)
            {
                try
                {
                    load.Add(new byte[10000]);
                }
                catch (OutOfMemoryException)
                {
                    Console.WriteLine("Out of memory. {0}", load.Count);
                }
            }
        });

        Console.WriteLine(GCSettings.IsServerGC);

        Task.Run(pollGC);
        Task.Run(doWork);

        Console.ReadLine();
        done = true;
        GC.CancelFullGCNotification();

        Thread.Sleep(2000);
    }
}

【问题讨论】:

标签: c# .net garbage-collection instrumentation


【解决方案1】:

如果你只需要知道GC花费了多少时间,你可以简单地使用CLR提供的memory performance counters。你试图重新发明的任何东西都不可靠。

您需要查找 % Time in GC 计数器。

显示用于执行某项任务的已用时间百分比 自上次垃圾收集周期以来的垃圾收集。这 计数器通常指示垃圾收集器完成的工作 代表应用程序收集和压缩内存。这个计数器 仅在每次垃圾回收结束时更新。这个计数器 不是平均值;它的值反映了最后观察到的值。

【讨论】:

  • 我已经在收集这些数据了……但是(除非我遗漏了什么)他们没有说 GC 花了多长时间。
  • @Darragh 他们怎么说呢?
  • 当垃圾收集运行时,大概需要一些时间?我想知道那是多少时间。
  • @Darragh 这就是性能计数器“% Time in GC”所说的。它会给你时间百分比。 This article 可能会给你一些想法
  • 那篇文章将 % Time in GC 计数器描述为“自上次 GC 结束以来花费在 GC 上的时间百分比”。这与垃圾收集运行所花费的时间有何相同之处?我想要一个以时间为单位测量的值。
猜你喜欢
  • 2010-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-10
  • 1970-01-01
  • 2012-06-28
  • 1970-01-01
  • 2016-11-18
相关资源
最近更新 更多