ภาพรวม
Stopwatch ใน System.Diagnostics ใช้วัดเวลาที่แม่นยำสูง (high-resolution) สำหรับ benchmarking และ profiling
โค้ดตัวอย่าง
using System;
using System.Diagnostics;
public class Demo {
public static void Main() {
Stopwatch sw = Stopwatch.StartNew();
// เรียกเมธอดที่ต้องการวัด
DoWork();
sw.Stop();
Console.WriteLine($"Elapsed: {sw.ElapsedMilliseconds} ms");
Console.WriteLine($"Elapsed: {sw.ElapsedTicks} ticks");
Console.WriteLine($"Elapsed: {sw.Elapsed}"); // TimeSpan format
}
static void DoWork() {
// จำลองงานหนัก
long sum = 0;
for (int i = 0; i < 10_000_000; i++) {
sum += i;
}
}
}
คุณสมบัติหลักของ Stopwatch
| Property/Method | คำอธิบาย |
|---|---|
| StartNew() | สร้างและเริ่มนับเวลาทันที (static factory) |
| Start() / Stop() | เริ่ม/หยุดนับเวลา |
| Reset() | รีเซ็ตเป็นศูนย์ |
| Restart() | Reset + Start |
| Elapsed | TimeSpan ของเวลาที่ผ่านไป |
| ElapsedMilliseconds | เวลาในมิลลิวินาที (long) |
| ElapsedTicks | จำนวน ticks (ความละเอียดสูงสุด) |
| IsRunning | กำลังนับเวลาอยู่หรือไม่ |
Best Practices
- ใช้
Stopwatch.StartNew()แทนnew Stopwatch() + Start() - วัดหลายรอบแล้วหาค่าเฉลี่ย เพื่อลด noise
- Warm-up: เรียกเมธอด 1-2 ครั้งก่อนวัดจริง (JIT compilation)
- ใช้
BenchmarkDotNetสำหรับ benchmarking ระดับมืออาชีพ
ตัวอย่าง Benchmark แบบครบถ้วน
using System;
using System.Diagnostics;
public class Benchmark {
public static void Main() {
const int iterations = 5;
long[] times = new long[iterations];
for (int i = 0; i < iterations; i++) {
Stopwatch sw = Stopwatch.StartNew();
DoWork();
sw.Stop();
times[i] = sw.ElapsedMilliseconds;
}
Console.WriteLine($"Times: {string.Join(", ", times)} ms");
Console.WriteLine($"Average: {times.Average():F2} ms");
Console.WriteLine($"Min: {times.Min()} ms");
Console.WriteLine($"Max: {times.Max()} ms");
}
static void DoWork() {
// workload
}
}