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