【C#】処理時間を計測する方法

「Stopwatch」クラスを使って処理時間を計測する方法をまとめます。

【検証環境】.NET Framework 4.7.2

サンプルコード

Console上に出力する場合

static void Main(string[] args)
{
    // Stopwatchクラス生成
    var sw = new System.Diagnostics.Stopwatch();

    // 計測開始
    sw.Start();

    ////計測したい処理を記述////

    // 計測停止
    sw.Stop();

    //結果出力
    Console.WriteLine($"処理時間 {sw.Elapsed}");
}

VisualStudio上に出力する場合

ASP.NETやWPFの場合はコンソールを表示できないので、VisualStudioに出力します。

static void Main(string[] args)
{
    // Stopwatchクラス生成
    var sw = new System.Diagnostics.Stopwatch();

    // 計測開始
    sw.Start();

    ////計測したい処理を記述////

    // 計測停止
    sw.Stop();

    //VisualStudio上に結果を出力する
    System.Diagnostics.Debug.WriteLine($"処理時間 {sw.Elapsed}");
}

Leave a Reply

Your email address will not be published. Required fields are marked *