C# 使用 StopWatch 檢測執行時間


參考 : [VB.Net][C#.Net] 測量 程式執行 時間 | 余小章 @ 大內殿堂 – 點部落


            Stopwatch sw = new Stopwatch();
            long num = 0;
            sw.Reset();
            sw = Stopwatch.StartNew();

            Thread.Sleep(1000);

            sw.Stop();
            TimeSpan el = sw.Elapsed;
            Console.WriteLine($"花費 {el}");

            long ms = sw.ElapsedMilliseconds;
            Console.WriteLine($"花費 {ms} 毫秒");

            long tk = sw.ElapsedTicks;
            Console.WriteLine($"花費 {tk} ticks");

試著改成繼承 IDisposable : 

    public class StopWatcher : IDisposable
    {
        private Stopwatch _stopWatch;

        public StopWatcher(Stopwatch sw)
        {
            _stopWatch = sw;
            sw.Reset();
            sw.Start();
        }

        public StopWatcher() : this(new Stopwatch()) { }
        public void Dispose()
        {
            _stopWatch.Stop();
            TimeSpan el = _stopWatch.Elapsed;
            Console.WriteLine($"花費 {el} ");

            long ms = _stopWatch.ElapsedMilliseconds;
            Console.WriteLine($"花費 {ms} 毫秒");

            long tk = _stopWatch.ElapsedTicks;
            Console.WriteLine($"花費 {tk} ticks");
        }
    }

print

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *