LoginSignup
1
1

More than 3 years have passed since last update.

[C#]StopWatchで処理にかかる時間を測る

Posted at

やりたいこと

時間がかかってそうな処理があるときに、その処理にどれくらいの時間がかかっているかを調べたい。

やり方

Stopwatchクラスを使う。

サンプルコード

測りたい処理を挟んで、Stopwatchをスタート~ストップして、時間を測る。

using System.Diagnostics;
using System.Threading;

namespace ConsoleApp5
{
    class Program
    {
        static void Main(string[] args)
        {
            // ストップウォッチを作成
            Stopwatch sw = new Stopwatch();

            // ストップウォッチをスタート
            sw.Restart();

            // 測りたい処理
            Thread.Sleep(5000);

            // ストップウォッチを止める
            sw.Stop();

            // 経過時間をsw.Elapsed や sw.ElapsedMilliseconds で取得
            Debug.WriteLine(" 経過時間:" + sw.ElapsedMilliseconds + " ms");
        }
    }
}

メモ

個人的に、スタートするときはRestart()を使う。
Start() → Stop() → Start() → Stop()とすると、一回目の時間をそのまま引き継いでしまうので、それに気づかないと間違った計測結果を採ってしまうので。

参考

Stopwatch Class
https://docs.microsoft.com/ja-jp/dotnet/api/system.diagnostics.stopwatch?view=netframework-4.8

1
1
0

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
1
1