How to calculate the execution time of c# application. I am having c# windows application in which i need to calculate the execution time and i dont have any idea where i have to proceed this. Can anyone please help me?
6 Answers
use Stopwatch of System.Diagnostics
static void Main(string[] args) { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Thread.Sleep(10000); 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("RunTime " + elapsedTime); } 4 Comments
You could, for instance, just use DateTime.Now before and after your execution and then subtract the milliseconds:
DateTime then = DateTime.Now; // Your code here DateTime now = DateTime.Now; Console.WriteLine(now.Millisecond - then.Millisecond); 4 Comments
Use the Benchmarking Made Easy library
A very easy and straightforward way is to use Jon Skeets Benchmarking Made Easy in C# toolset. Even with StopWatch, you still find yourself writing a lot of code around each bit you want to benchmark.
The benchmark toolset makes this trivial: you just hand it one or more functions and give them variable input and they will run until finished. The results for each function can then be introspected or printed to screen.
Comments
Write a static class and write the above code in a static method... call that method where ever you want to use the timer
1 Comment
You can use the built-in profiler for the same, it's available in VS2010 Premium and Ultimate under Main Menu -> Analyze -> Profiler