在不调试每一行的情况下执行方法需要多少时间?

问题描述 投票:0回答:1

是否可以在 Visual Studio 或其他实用程序或程序中查看以下方法已执行了多长时间?这是一个简化版本,但是我有很多行代码,很难看出一个方法一个方法执行花费了多少时间:

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

及其实施:

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

是的,我知道在调试以下功能时是可能的:

image description

但是我想执行很多代码,并且我想查看一个方法列表,该列表显示在不调试每段代码的情况下执行代码所需的时间。 Visual Studio 中是否有一些工具或者可能是替代工具?

c# visual-studio profiling profiler
1个回答
0
投票

有一种可能的方法,你可以清楚地看到每个方法的执行时间列表,但你必须调试代码,使用“stopwatch”类来测量每个方法的执行时间,如下代码,你可以尝试运行它。希望能帮到你。

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

此外,您还可以使用Visual Studio中的Performance Profiler来实现方法级别的性能分析。

© www.soinside.com 2019 - 2024. All rights reserved.