Class Stopwatch (namespace System.Diagnostics) cung cấp cách chính xác nhất để đo thời gian thực thi code trong .NET.
Ví dụ cơ bản
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Stopwatch sw = Stopwatch.StartNew();
// Code cần đo
DoWork();
sw.Stop();
Console.WriteLine($"Thời gian: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Thời gian: {sw.ElapsedTicks} ticks");
Console.WriteLine($"Thời gian: {sw.Elapsed.TotalMilliseconds:F3} ms");
}
static void DoWork()
{
// Giả lập công việc
long sum = 0;
for (int i = 0; i < 10_000_000; i++)
sum += i;
}
}
Đo nhiều lần (benchmark)
static void Benchmark(Action action, int iterations = 5)
{
for (int i = 0; i < iterations; i++)
{
Stopwatch sw = Stopwatch.StartNew();
action();
sw.Stop();
Console.WriteLine($"Lần {i+1}: {sw.ElapsedMilliseconds} ms");
}
}
// Sử dụng
Benchmark(() => DoWork(), 10);
Kết quả đầu ra (ví dụ)
Lần 1: 12 ms Lần 2: 10 ms Lần 3: 11 ms Lần 4: 10 ms Lần 5: 11 ms
Mẹo: Dùng BenchmarkDotNet cho benchmark chuyên nghiệp (warm-up, GC, statistical analysis).