DateTime startTime = DateTime.Now;
// Some Execution Process
DateTime endTime = DateTime.Now;
TimeSpan totalTimeTaken = endTime.Subtract(startTime);
Now, does DateTime.Now accurately measure performance? No, it does not. DateTime.Now, according to MSDN has a resolution of ~16ms, which means it is not very precise.
Environment.TickCount
Another approach would to use system tickcount as kept by Environment.TickCount. This keeps the number of milliseconds since the computer was started. Unfortunately it is stored as a signed int, so every 49 days it is actually counting backwards. We can compensate for this by just taking off the most siginificant bit.
Stopwatch
Another better approach is to use Stopwatch. System.Diagnostics offers Stopwatch that automatically checks for high precision timers. You can check if the Stopwatch is using high-precision timers by checking via Stopwatch.IsHighResolution() method.
Stopwatch swTimer = Stopwatch.StartNew();
//Some execution process here
foo()
swTimer.Stop();
Watch for the difference in the code results
protected void Page_Load(object sender, EventArgs e)
{
DateTime sStartTime, sEndTime;
TimeSpan tsTotalTimeTaken;
sStartTime = DateTime.Now;
for (long lCount = 0; lCount < 100; lCount++)
{
Thread.Sleep(1);
}//for(int iCount=0; iCount<100; iCount++)
sEndTime = DateTime.Now;
Stopwatch swTimer = Stopwatch.StartNew();
for (long lCount = 0; lCount < 100; lCount++)
{
Thread.Sleep(1);
}//for(int iCount=0; iCount<100; iCount++)
swTimer.Stop();
tsTotalTimeTaken = sEndTime.Subtract(sStartTime);
Response.Write("Elaspsed Time according to DateTime.Now(): " + tsTotalTimeTaken.Milliseconds + "
");
Response.Write("Elapsed Time according to StopWatch(): " + swTimer.Elapsed.Milliseconds);
}
Output: