ZihamZuhair
ZihamZuhair

Reputation: 43

Get Average execution time of a method C#

This method works fine. But I want to know if there's any other way or make this method more accurate and my ultimate goal is to run the same method 10 times and get the average execution time of it.

   public static void Measure(Action action, int noOfTimesToRunThisMethod)
   {
        long averageTime = 0;

        GC.Collect();  
        GC.WaitForPendingFinalizers();    
            
        Console.WriteLine("Started");

        for (int i = 1; i <= noOfTimesToRunThisMethod; i++)
        {
           Stopwatch watch = Stopwatch.StartNew();              
           action();
           watch.Stop();
           Console.WriteLine($"Attempt:{i.ToString("D2")} Time Taken:{watch.ElapsedMilliseconds} ms");
           averageTime += watch.ElapsedMilliseconds;
        }
        Console.WriteLine($"Average: {averageTime/ noOfTimesToRunThisMethod}");
   }

To use this helper method

   var noOfTimesToRunThisMethod = 10;
           
   Utils.Measure(() => 
   {  
     MyMethod(arr)
   },noOfTimesToRunThisMethod);

Upvotes: 0

Views: 648

Answers (1)

Farhad Zamani
Farhad Zamani

Reputation: 5861

You can use Benchmark to test your execution method time. there is an example of Benchmark:

public class Program
{
    public static void Main()
    {
        BenchmarkRunner.Run<ListMemoryAllocationTest>();
    }
}
[MemoryDiagnoser]
public class ListMemoryAllocationTest
{
    public int Count { get; set; } = 900000;
    [Benchmark]
    public void DefaultConstructor()
    {
        List<int> numbers = new List<int>();
        for (int i = 0; i < Count; i++)
        {
            numbers.Add(i);
        }
    }
    [Benchmark]
    public void AddCountToConstructor()
    {  
        List<int> secondNumbers = new List<int>(Count);
        for (int i = 0; i < Count; i++)
        {
            secondNumbers.Add(i);
        }
    }
}

Change your project configuration from Build to Release and Run project.

Result:

|                Method |     Mean |    Error |   StdDev |    Gen 0 |    Gen 1 |    Gen 2 | Allocated |

|    DefaultConstructor | 753.4 us | 14.80 us | 15.20 us | 628.9063 | 627.9297 | 237.3047 |  1,024 KB |
| AddCountToConstructor | 499.6 us |  9.86 us | 17.78 us | 255.8594 | 255.8594 |  95.7031 |    391 KB |

Upvotes: 1

Related Questions