Search code examples
c#stopwatch

C# Stopwatch to calculate loop time for function


I am not familiar with the C# stopwatch class. I am trying to find elapsed time for a function. When I call a function again I need to get the total time since the last call. How Should I do it?

I thought something like below:

public double CalculateAngle(double Theta_dot, double Psi_dot)
{
    mywatch.Stop();
    var time = mywatch.ElapsedMilliseconds / 1000;
    mywatch.Start();
}

Solution

  • If you want to measure the time since the last time the method was called then use Restart:

    Use Restart to stop current interval measurement and start a new interval measurement.

    public double CalculateAngle(double Theta_dot, double Psi_dot)
    {
       TimeSpan ts = sw.Elapsed;
       mywatch.Restart();
    }
    

    Depending on what you're trying to achieve you'd put restart at the start or end of the method...