When you do performance optimization or something similar you will need to determine the execution time for a particular method call or a piece of code. Here is some code that you can use in those scenarios. Either StopWatch or DateTime can be used to do this.
Using System.Diagnostics.Stopwatch
Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); // Your code, it could be in-line code, a web service call or whatever code you want to analyse, goes here stopWatch.Stop(); // Get the elapsed time as a TimeSpan value. TimeSpan ts = stopWatch.Elapsed; // Format and display the TimeSpan value. string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); Console.WriteLine("Time taken : " + elapsedTime); // Or you can just call ToString() on TimeSpan var "ts" Console.WriteLine("RunTime " + ts.ToString());
Using DateTime
DateTime start = DateTime.Now; // Your code, it could be in-line code, a web service call or whatever code you want to analyse, goes here DateTime end = DateTime.Now; TimeSpan ts = end - start; Console.WriteLine("Time taken : " + ts.ToString());
No comments:
Post a Comment