计算 C# 中方法的执行时间

csharpprogrammingserver side programming更新于 2025/9/18 13:18:00

使用 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

相关文章