计算 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-06-2020

685 次浏览

开始您的职业生涯

获取认证证书完成课程

开始
广告
© . All rights reserved.