Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

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