Measuring Code Execution Time with C#
When we need to find out how long the code we wrote takes to run, we can use the Stopwatch object in .NET.
Let's add the required namespace:
using System.Diagnostics;
And our code looks like this:
Stopwatch izle = new Stopwatch();
izle.Start();
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
izle.Stop();
MessageBox.Show("Connection time: {0}", izle.Elapsed.Milliseconds);
The measurement is started with Start and ended with Stop, and the elapsed time is held in the Elapsed variable. You can get it as Hours, Minutes, Seconds or Miliseconds.