Measure execution time in C#

前端 未结 8 638
广开言路
广开言路 2020-12-13 18:12

I want to measure the execution of a piece of code and I\'m wondering what the best method to do this is?

Option 1:

DateTime StartTime = DateTime.Now         


        
8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-13 18:44

    I took Hamish's answer simplified it and made it a bit more general in case you need to log to somewhere else:

    public class AutoStopWatch : Stopwatch, IDisposable {
    
        public AutoStopWatch() {
            Start();
        }
    
        public virtual void Dispose() {
            Stop();
        }
    }
    
     public class AutoStopWatchConsole : AutoStopWatch {
    
        private readonly string prefix;
    
        public AutoStopWatchConsole(string prefix = "") {
            this.prefix = prefix;
        }
    
        public override void Dispose() {
            base.Dispose();
    
            string format = Elapsed.Days > 0 ? "{0} days " : "";
            format += "{1:00}:{2:00}:{3:00}.{4:00}";
    
            Console.WriteLine(prefix + " " + format.Format(Elapsed.Days, Elapsed.Hours, Elapsed.Minutes, Elapsed.Seconds, Elapsed.Milliseconds / 10));
        }
    }
    
    private static void Usage() {
    
        Console.WriteLine("AutoStopWatch Used: ");
        using (var sw = new AutoStopWatch()) {
            Thread.Sleep(3000);
    
            Console.WriteLine(sw.Elapsed.ToString("h'h 'm'm 's's'"));
        }
    
        Console.WriteLine("AutoStopWatchConsole Used: ");
        using (var sw = new AutoStopWatchConsole()) {
            Thread.Sleep(3000);
        }
    
    }
    

提交回复
热议问题