Sử dụng lớp Đồng hồ bấm giờ để đo thời gian thực thi một phương thức trong .NET -
Stopwatch s = Stopwatch.StartNew();
Bây giờ, hãy đặt một hàm và sử dụng thuộc tính ElapsedMilliseconds để có thời gian thực thi tính bằng mili giây -
s.ElapsedMilliseconds
Hãy cho chúng tôi xem mã hoàn chỉnh -
Ví dụ
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!");
}
} Đầu ra
Demo function! Time taken: 15ms Time taken: 16ms Time taken: 16ms Time taken: 16ms Time taken: 16ms