System.Diagnostics.Stopwatch で AverageTimer32 および AverageBase パフォーマンス カウンターを使用するにはどうすればよいでしょうか? 質問する

System.Diagnostics.Stopwatch で AverageTimer32 および AverageBase パフォーマンス カウンターを使用するにはどうすればよいでしょうか? 質問する

次のプログラムを実行してパフォーマンス カウンターを見ると、結果が意味をなさないことがわかります。平均値はゼロで、最小値/最大値は ~0.1 または ~100 を期待するところ ~0.4 です。

私の問題は何ですか?

コード

class Program
{
    const string CategoryName = "____Test Category";
    const string CounterName = "Average Operation Time";
    const string BaseCounterName = "Average Operation Time Base";

    static void Main(string[] args)
    {
        if (PerformanceCounterCategory.Exists(CategoryName))
            PerformanceCounterCategory.Delete(CategoryName);

        var counterDataCollection = new CounterCreationDataCollection();

        var avgOpTimeCounter = new CounterCreationData()
        {
            CounterName = CounterName,
            CounterHelp = "Average Operation Time Help",
            CounterType = PerformanceCounterType.AverageTimer32
        };
        counterDataCollection.Add(avgOpTimeCounter);

        var avgOpTimeBaseCounter = new CounterCreationData()
        {
            CounterName = BaseCounterName,
            CounterHelp = "Average Operation Time Base Help",
            CounterType = PerformanceCounterType.AverageBase
        };
        counterDataCollection.Add(avgOpTimeBaseCounter);

        PerformanceCounterCategory.Create(CategoryName, "Test Perf Counters", PerformanceCounterCategoryType.SingleInstance, counterDataCollection);

        var counter = new PerformanceCounter(CategoryName, CounterName, false);
        var baseCounter = new PerformanceCounter(CategoryName, BaseCounterName, false);

        for (int i = 0; i < 500; i++)
        {
            var sw = Stopwatch.StartNew();
            Thread.Sleep(100);
            sw.Stop();

            Console.WriteLine(string.Format("t({0}) ms({1})", sw.Elapsed.Ticks, sw.Elapsed.TotalMilliseconds));
            counter.IncrementBy(sw.Elapsed.Ticks);
            baseCounter.Increment();
        }

        Console.Read();
    }
}

パフォーマンスカウンターのスクリーンショット パフォーマンス カウンターのスクリーンショット http://friendfeed-media.com/50028bb6a0016931a3af5122774b56f93741bb5c

ベストアンサー1

System.Diagnostics API には、大きな混乱を招く微妙な原因が含まれています。System.Diagnostics の「ティック」は、DateTime または TimeSpan の「ティック」と同じではありません。

使用する場合はストップウォッチ.経過ティックStopWatch.Elapsed.Ticks の代わりに使用すると動作するはずです。

ドキュメンテーションこれに関する詳細情報が記載されています。

おすすめ記事