LoginSignup
2
3

More than 5 years have passed since last update.

デリゲートを使った時間計測用メソッド

Posted at

コーディングや設計をしている時に、どんな書き方をすれば早いのかと思って、簡単に時間を測る事があります。

その際に、各処理の前後にStopwatchをStart、Stopと書き、掛かった時間を出力するのですが、
いちいち書くのめんどくさいなと思って、メソッドに纏めてみました。

ソースコード


Stopwatch watch = new Stopwatch();

private void MeasurementClock(Action method)
{
    watch.Reset();
    watch.Start();

    // 計測するメソッド本体
    method();

    watch.Stop();

    // 計測メソッド名の取得
    string methodName = method.Method.Name;

    Console.WriteLine($@"メソッド名:{methodName}
                        計測時間:{watch.Elapsed.Milliseconds:n0}ミリ秒");
}


使い方例


using System;
using System.Diagnostics;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        /// <summary>
        /// メイン処理
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            var main = new Program();

            // ここで計測したいメソッド名を引数にして呼ぶ。
            main.MeasurementClock(main.StringBuilder);
            main.MeasurementClock(main.StringConcat);

        }

        Stopwatch watch = new Stopwatch();
        string Id = "Id0001";
        int loopCount = 10000;

        /// <summary>
        /// 計測用メソッド
        /// </summary>
        /// <param name="method"></param>
        private void MeasurementClock(Action method)
        {
            watch.Reset();
            watch.Start();

            // 計測するメソッド本体
            method();

            watch.Stop();

            // 計測メソッド名の取得
            string methodName = method.Method.Name;

            Console.WriteLine($@"メソッド名:{methodName}
                                計測時間:{watch.Elapsed.Milliseconds:n0}ミリ秒");
        }

        private void StringBuilder()
        {
            StringBuilder sb = new StringBuilder();
            string display = string.Empty;
            for ( int i = 0; i < loopCount; i++ )
            {
                sb.Append(Id)
                    .Append(Id)
                    .Append(Id)

                    .Append(i);
            }

            display = sb.ToString();
        }

        private void StringConcat()
        {
            string display = string.Empty;
            for ( int i = 0; i < loopCount; i++ )
            {
                display += Id + Id + Id + i;
            }
        }
    }
}


2
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3