How to measure the execution time of a method in C#

1 Answer

0 votes
using System;

public class MeasureExecutionTimeOfMethod_CSharp
{
    public static long AMethod() {
        long sum = 0;

        for (int i = 0; i < 100000; i++) {
            sum += i;
        }

        return sum;
    }

    public static void Main(string[] args)
    {
        long startTime = DateTime.Now.Ticks;

        long result = AMethod();

        long endTime = DateTime.Now.Ticks;
        long elapsedTime = endTime - startTime;

        Console.WriteLine("Execution time in nanoseconds: " + (elapsedTime * 100));
        Console.WriteLine("Execution time in milliseconds: " + (elapsedTime / (TimeSpan.TicksPerMillisecond + 0.0)));
    }
}



/*
run:
 
Execution time in nanoseconds: 13281000
Execution time in milliseconds: 13.281
 
*/

 



answered Aug 4, 2024 by avibootz

Related questions

1 answer 134 views
1 answer 123 views
2 answers 198 views
4 answers 211 views
211 views asked Mar 28, 2023 by avibootz
2 answers 158 views
2 answers 155 views
...