The Stopwatch class in System.Diagnostics namespace provides a set of methods and properties that you can use to accurately measure elapsed time.
The following example uses the Stopwatch class to measure the performance of four different implementations for parsing an integer from a string.
using System.Diagnostics;
public static void TestIntParse(int operation)
{
long ticksThisTime = 0;
int inputNum;
Stopwatch timePerParse;
string desc = string.Empty;
switch (operation)
{
case 0:
// Parse a valid integer using
// a try-catch statement.
desc = "Int32.Parse(\"0\")";
// Start a new stopwatch timer.
timePerParse = Stopwatch.StartNew();
try
{
inputNum = Int32.Parse("0");
}
catch (FormatException)
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse.Stop();
ticksThisTime = timePerParse.ElapsedTicks;
break;
case 1:
// Parse a valid integer using
// the TryParse statement.
desc = "Int32.TryParse(\"0\" out input)";
// Start a new stopwatch timer.
timePerParse = Stopwatch.StartNew();
if (!Int32.TryParse("0", out inputNum))
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse.Stop();
ticksThisTime = timePerParse.ElapsedTicks;
break;
case 2:
// Parse an invalid value using
// a try-catch statement.
desc = "Int32.Parse(\"a\")";
// Start a new stopwatch timer.
timePerParse = Stopwatch.StartNew();
try
{
inputNum = Int32.Parse("a");
}
catch (FormatException)
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse.Stop();
ticksThisTime = timePerParse.ElapsedTicks;
break;
case 3:
// Parse an invalid value using
// the TryParse statement.
desc = "Int32.TryParse(\"a\" out input)";
// Start a new stopwatch timer.
timePerParse = Stopwatch.StartNew();
if (!Int32.TryParse("a", out inputNum))
{
inputNum = 0;
}
// Stop the timer, and save the
// elapsed ticks for the operation.
timePerParse.Stop();
ticksThisTime = timePerParse.ElapsedTicks;
break;
default:
break;
}
double ms = (ticksThisTime * 1000.0) / Stopwatch.Frequency;
Console.WriteLine(string.Format("{0} spents {1} milliseconds.", desc, ms));
}
public static void Main()
{
TestIntParse(0);
TestIntParse(1);
TestIntParse(2);
TestIntParse(3);
}