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;
//Code
TimeSpan ts = DateTime.Now.Subtract(StartTime);
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");
Option 2: using System.Diagnostics;
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//Code
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(elapsedTime, "RunTime");
This isn't simply for benchmarking, its actually part of the application. The time the function takes to execute is relevant data. It doesn't however need to be atomic or hyper-accurate.
Which option is better for production code, or does anybody else use something different and perhaps better?
I took Hamish's answer simplified it and made it a bit more general in case you need to log to somewhere else:
Use below code
It's not just that
StopWatch
is more accurate, but also thatDateTime.Now
will give incorrect results in some circumstances.Consider what happens during a daylight saving time switch-over, for example — using
DateTime.Now
can actually give a negative answer!I have a little class to do this sort of thing ad hoc. It uses the stopwatch class - c# micro perfomance testing.
eg.
The
Stopwatch
class is specifically designed to measure elapsed time and may (if available on your hardware) provide good granularity/accuracy using an underlying high-frequency hardware timer. So this seem the best choice.The IsHighResolution property can be used to determine whether high resolution timing is available. Per the documentation, this class offers a wrapper on the 'best available' Win32 APIs for accurate timing:
There is detailed background on those Win32 APIs [here] and in linked MSDN docs 2.
Both will likely fit your needs just fine, but I would say use
StopWatch
. Why? Cause it's meant for the task you're doing.You've got one class that's built to return the current date/time, which as it happens can be used for timing things, and you've got one class specifically designed for timing things.
In this case the differences only really exist if you need millisecond accuracy (In which case
StopWatch
is more accurate), but as a general principal if a tool exists specifically for the task you're looking for then it's the better one to use.