用 C# 計算方法的執行時間


使用 Stopwatch 類測量 .NET 中方法的執行時間 -

Stopwatch s = Stopwatch.StartNew();

現在設定一個函式並使用 ElapsedMilliseconds 屬性以毫秒為單位獲取執行時間 -

s.ElapsedMilliseconds

讓我們看看完整的程式碼 -

示例

 即時演示

using System;
using System.IO;
using System.Diagnostics;

public class Demo {
   public static void Main(string[] args) {
      Stopwatch s = Stopwatch.StartNew();
      display();

      for (int index = 0; index < 5; index++) {
         Console.WriteLine("Time taken: " + s.ElapsedMilliseconds + "ms");
      }
      s.Stop();
   }
   public static void display() {
      Console.WriteLine("Demo function!");
   }
}

輸出

Demo function!
Time taken: 15ms
Time taken: 16ms
Time taken: 16ms
Time taken: 16ms
Time taken: 16ms

更新於: 22-6 月 -2020

686 次瀏覽

開啟你的 職業

透過完成本課程獲得認證

開始
廣告
© . All rights reserved.