0

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();
}
fatihyildizhan
  • 8,614
  • 7
  • 64
  • 88
Htekin
  • 29
  • 4
  • Have a look at teh TimeSpan class – Aldert Dec 24 '22 at 10:44
  • Have a look at: [Exact time measurement for performance testing](https://stackoverflow.com/questions/969290/exact-time-measurement-for-performance-testing) and [How to measure code performance in .NET?](https://stackoverflow.com/questions/457605/how-to-measure-code-performance-in-net). – Luuk Dec 24 '22 at 10:46
  • 1
    What is supposed to happen on first call? What's the intent of the measurement? – Fildor Dec 24 '22 at 10:54

2 Answers2

2

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

tymtam
  • 31,798
  • 8
  • 86
  • 126
1

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.

Yigit Pilevne
  • 506
  • 6
  • 14