方法的操作时间

lov*_*iji 4 c#

怎么知道,在C#中采用多少时间方法,例如,我有label1和方法

    public int MakeSome(int a, int b)
    {

        for (int i = 0; i < a; i++)
        {
            for (int j = 0; j < b; j++)
            {
               // some operation
            }
        }
        return returnIntValue;
    }
Run Code Online (Sandbox Code Playgroud)

知道,如何知道MakeSome方法需要多少毫秒,并在label1中写入值.谢谢

CMS*_*CMS 14

你可以使用这个Stopwatch类:

Stopwatch st = new Stopwatch();
st.Start();
// call MakeSome method...
st.Stop();
Run Code Online (Sandbox Code Playgroud)

然后你可以检查st.ElapsedMilliseconds财产.


Eri*_*ert 11

使用System.Diagnostics命名空间中的Stopwatch类.

  • 我不知道.你在循环中做什么?另外,不要忘记您可能正在测量抖动所花费的时间; 第一次运行代码时,如果加载程序集,运行静态初始化程序等,则可能会比第二次运行更长的数量级. (2认同)