Htekin
Htekin

Reputation: 29

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();
}

Upvotes: 0

Views: 1056

Answers (2)

tmaj
tmaj

Reputation: 35115

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...

Upvotes: 2

Yigit Pilevne
Yigit Pilevne

Reputation: 555

You can store execution times in a global list.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;

public class Program
{
    public static List<long> executionTimes = new List<long>();
    public static void Main()
    {
        Stopwatch watch = new Stopwatch();
        for (int i = 0; i < 10; i++)
        {
            watch.Start();
            MyFunction();
            var elapsed = watch.ElapsedMilliseconds;
            executionTimes.Add(elapsed);
        }
    
        Console.WriteLine(String.Join("; ", executionTimes));
    }
    public static async Task MyFunction()
    {
        //your function...
    }
}

If you need, you can use Stop() or Restart() methods of watch.

Upvotes: 1

Related Questions