Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วัดเวลาการทำงานของเมธอดด้วย Stopwatch ใน C#

ภาพรวม

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
ElapsedTimeSpan ของเวลาที่ผ่านไป
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
    }
}