Search code examples
c#visual-studioprofilingprofiler

How much time does it take to execute the methods without debugging each line?


Is it possible to see in Visual Studio or other utilies or programms how much time the following methods have been executed? This is a simplified version, but I have a lot of lines of code and it becomes hard to see how much time it took to execute method by method:

Foo foo = new ();
foo.Method_1(); // it takes 1 second to be executed
foo.Method_2(); // it takes 2 second to be executed
foo.Method_3(); // it takes 3 second to be executed

and its implementation:

public class Foo
{
    public void Method_1()
    {
        Thread.Sleep(1000);
    }
    
    public void Method_2()
    {
        Thread.Sleep(2000);
    }
    
    public void Method_3()
    {
        Thread.Sleep(3000);
    }
}

Yeah, I know it is possible to see measurements while debugging:

image description

But I want to execute a lot of code and I would like to see a list of methods which shows how much time it takes to execute code without debugging every piece of code. Is there any some tools in Visual Studio or maybe is alternative tools?


Solution

  • There is a possible way that you can see a list of execution time of every method clearly but you must debug codes, using 'stopwatch' class to measure the execution time of each method as the following code, you can try to run it. I hope it can help you.

    class Program
    {
        static void Main(string[] args)
        {
            // Calls the Timewatch method, passing a method to execute as an argument
            Timewatch(Method_1);
            Timewatch(Method_2);
            Timewatch(Method_3);
        }
        static void Timewatch(Action method)
        {
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            // Execute the method passed in
            method();
            stopwatch.Stop();
            Console.WriteLine("execution time:" + stopwatch.Elapsed);
            stopwatch.Reset();
        }
        static void Method_1()
        {
            System.Threading.Thread.Sleep(1000);
            // it takes 1 second to be executed
        }
    
        static void Method_2()
        {
            System.Threading.Thread.Sleep(2000);
            // it takes 2 second to be executed
        }
    
        static void Method_3()
        {
            System.Threading.Thread.Sleep(3000);
            // it takes 3 second to be executed
        }
    }
    

    What's more, you can also use Performance Profiler in Visual Studio to implement method level performance analysis.