如何测量函数运行的时间?

seb*_*ibu 39 .net c# performance timer stopwatch

我想看一个函数运行多长时间.所以我在表单上添加了一个计时器对象,我出来了这段代码:

private int counter = 0;

// Inside button click I have:
timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Stop();
Run Code Online (Sandbox Code Playgroud)

和:

private void timer_Tick(object sender, EventArgs e)
{
    counter++;
    btnTabuSearch.Text = counter.ToString();
}
Run Code Online (Sandbox Code Playgroud)

但这并不算什么.为什么?

Oma*_*mar 50

为了避免将来出现计时器问题,这里是正确的代码:

timer = new Timer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = 1; //set interval on 1 milliseconds
timer.Enabled = true; //start the timer
Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);
timer.Enabled = false; //stop the timer
Run Code Online (Sandbox Code Playgroud)
private void timer_Tick(object sender, EventArgs e)
{
   counter++;
   btnTabuSearch.Text = counter.ToString();
}
Run Code Online (Sandbox Code Playgroud)

但这是错误的方法.您必须使用秒表(System.Diagnostic)类,因为它是一个高分辨率计时器,而Diagnostic这个词说明了一切.

试试这个:

Stopwatch timer = Stopwatch.StartNew();

Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

timer.Stop();  
TimeSpan timespan = timer.Elapsed;

btnTabuSearch.Text = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds / 10);
Run Code Online (Sandbox Code Playgroud)

  • 注意:如果定时器设置的间隔为1ms,则应注意不要认为计数器实际上是毫秒数.根据硬件的不同,计时器(在我的计算机上)的最小间隔约为15毫秒.因此,即使您将间隔设置为1毫秒,它也只会每隔15毫秒开一次. (4认同)
  • `var timer = Stopwatch.StartNew();`< - 少一行代码 (2认同)

Ode*_*ded 45

不要使用计时器 - 使用该Stopwatch课程.

var sw = new Stopwatch();
Result result = new Result();

sw.Start();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

sw.Stop();

// sw.Elapsed tells you how much time passed
Run Code Online (Sandbox Code Playgroud)

  • 甚至`var sw = Stopwatch.StartNew();`< - 少一行代码 (9认同)

Ala*_*ain 11

查看运行代码需要多长时间的最佳方法是使用System.Diagnostics.Stopwatch.

这是一个例子:

using System.Diagnostics;

#if DEBUG
     Stopwatch timer = new Stopwatch();
     timer.Start();
#endif

     //Long running code

#if DEBUG
     timer.Stop();
     Debug.WriteLine("Time Taken: " + timer.Elapsed.TotalMilliseconds.ToString("#,##0.00 'milliseconds'"));
#endif
Run Code Online (Sandbox Code Playgroud)

我使用它#if DEBUG来确保秒表代码没有进入生产版本,但你可以没有它.


jam*_*wis 11

您应该使用秒表类进行计时功能.

请尝试以下方法:

private int counter = 0;

// setup stopwatch and begin timing
var timer = System.Diagnostics.Stopwatch.StartNew();

Result result = new Result();
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia);

// stop timer and get elapsed time
timer.Stop();
var elapsed = timer.Elapsed;

// display result time
MessageBox.Show(elapsed.ToString("mm':'ss':'fff"));
Run Code Online (Sandbox Code Playgroud)


bat*_*aci 11

Visual Studio 2015,2017 Professional和Enterprise具有诊断工具.如果函数末尾有断点,它将在" 事件"选项卡下显示时间和持续时间,如图所示:

在此输入图像描述

您可以在Visual Studio 2015中查看文章Diagnostic Tools调试器窗口以获取更多详细信息.

PS; 到目前为止只有Xamarin表单,跨平台项目不支持此功能.我希望微软为xamarin表单项目带来这个伟大的功能.


Nik*_*wal 7

使用System.Diagnostics的秒表:

static void Main(string[] args)
{
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    Thread.Sleep(10000);
    stopWatch.Stop();

    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;

    // Format and display the TimeSpan value.
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
}
Run Code Online (Sandbox Code Playgroud)

  • 使用`ts.ToString("hh:mm:ss.ff")`或`ts.ToString("G")`来打印时间会不会更容易? (3认同)

Mat*_*and 6

要对功能进行计时,您应该使用秒表类

此外,您的计时器不计数的原因是您没有为它设置间隔.


Phi*_*ppe 6

一种可能性是编写一次这样的辅助方法:

    public static void Time(Action action)
    {
        Stopwatch st = new Stopwatch();
        st.Start();
        action();
        st.Stop();
        Trace.WriteLine("Duration:" + st.Elapsed.ToString("mm\\:ss\\.ff"));
    }
Run Code Online (Sandbox Code Playgroud)

并在其他地方使用它来测量时间,如下所示:

    Time(() =>
    {
     CallOfTheMethodIWantToMeasure();
    });
Run Code Online (Sandbox Code Playgroud)