Measure execution time
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| C# Code Snippets |
| See also |
| edit |
This C# code snippet measures a time interval as you would measure the execution time of a task.
DateTime startTime = DateTime.Now; Console.WriteLine ("Started: {0}", startTime); // Execute the task to be timed for (int i=1; i < 100000; i++){} DateTime stopTime = DateTime.Now; Console.WriteLine ("Stopped: {0}", stopTime); TimeSpan elapsedTime = stopTime - startTime; Console.WriteLine ("Elapsed: {0}", elapsedTime); Console.WriteLine ("in hours :" + elapsedTime.TotalHours); Console.WriteLine ("in minutes :" + elapsedTime.TotalMinutes); Console.WriteLine ("in seconds :" + elapsedTime.TotalSeconds); Console.WriteLine ("in milliseconds:" + elapsedTime.TotalMilliseconds);
In C# 2.0, the same thing can be done as follows:
Stopwatch watch = new Stopwatch(); watch.Start(); for (int i = 1; i < 1000000; i++) { } // Execute the task to be timed watch.Stop(); Console.WriteLine("Elapsed: {0}",watch.Elapsed); Console.WriteLine("In milliseconds: {0}",watch.ElapsedMilliseconds); Console.WriteLine("In timer ticks: {0}",watch.ElapsedTicks);
For DateTime formatting options, refer to Format the date and time.