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
Neither will hurt the performance, because you say it is not that critical. StopWatch seems more appropriate - you are only subtracting time from time and not one date from another. Date stuff takes a tad more memory and CPU time to deal with. There are also ways to make the code cleaner, in case you plan on reusing it in several places. Overloading using
comes to mind. I will search for an example. Ok, code stolen from:
http://stevesmithblog.com/blog/great-uses-of-using-statement-in-c/
public class ConsoleAutoStopWatch : IDisposable
{
private readonly Stopwatch _stopWatch;
public ConsoleAutoStopWatch()
{
_stopWatch = new Stopwatch();
_stopWatch.Start();
}
public void Dispose()
{
_stopWatch.Stop();
TimeSpan ts = _stopWatch.Elapsed;
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
ts.Hours, ts.Minutes, ts.Seconds,
ts.Milliseconds / 10);
Console.WriteLine(elapsedTime, "RunTime");
}
}
private static void UsingStopWatchUsage()
{
Console.WriteLine("ConsoleAutoStopWatch Used: ");
using (new ConsoleAutoStopWatch())
{
Thread.Sleep(3000);
}
}
Use below code
DateTime dExecutionTime;
dExecutionTime = DateTime.Now;
TimeSpan span = DateTime.Now.Subtract(dExecutionTime);
lblExecutinTime.Text = "total time taken " + Math.Round(span.TotalMinutes,2) + " minutes . >>---> " + DateTime.Now.ToShortTimeString();