C#のパフォーマンスカウンタ

『プログラミング .NET Framework 第2版』に簡単便利なパフォーマンスカウンタのコードがあったのでメモしておきます。

using System;
using System.Collections;
using System.Collections.Generic;
using Systme.Diagnostics;

internal sealed class OperationTimer : IDisposable {
	private Int64 m_startTime;
	private String m_text;
	private Int32 m_collectionCount;

	public OperationTimer(Sring text){
		PrepareForOperation();
		m_text	=	text;
		m_collectionCount	=	GC.CollectionCount(0);
		m_startTime	=	Stopwatch.GetTimestamp();
	}

	public void Dispose() {
		Console.WriteLine("{0,6:###.00} seconds (GCs={1,3}) {2}",
			(Double) Stopwatch.Frequency,
		GC.CollectionCount(0) - m_collectionCount, m_text);
	}

	private static void PrepareForOperation() {
		GC.Collect();
		GC.WaitForPendingFinalizers();
		GC.Collect();
	}
}

以下のように使います。

using System;

public static class Program {
        public static void Main() {
                using (new OperationTimer("何かの処理")){
                        // 時間を計測したい処理を書く。
                }
        }
}