如何衡量一个函数运行多久?如何衡量一个函数运行多久?(How do I measure how lo

2019-05-13 12:09发布

我希望看到一个功能正在运行多久。 所以,我说我的窗体上的计时器对象,我想出了这样的代码:

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();

和:

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

不过这还不算什么。 为什么?

Answer 1:

为了避免与定时器未来的问题,这里是正确的代码:

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

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

但这是错误的形式给出。 您必须使用秒表(System.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);


Answer 2:

不要使用计时器-使用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


Answer 3:

看到一些代码需要多长时间运行的最好方法是使用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

我用的是#if DEBUG确保秒表代码不会进入产能释放,但你可以没有它。



Answer 4:

您应该使用秒表类的定时功能。

尝试以下方法:

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"));


Answer 5:

Visual Studio的2015年 ,2017年专业版和企业拥有的诊断工具。 如果你有你的函数结束一个断点,它会显示活动选项卡下的时间和持续时间显示的图像:

你可以看到这篇文章在Visual Studio 2015年诊断工具调试器窗口的更多细节。

PS; 到目前为止,只有Xamarin的形式,跨平台项目的犯规支持此功能。 我希望微软带来了这个伟大的功能对于xamarin形式的项目也是如此。



Answer 6:

使用秒表 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);
}


Answer 7:

对于时间的函数,你应该使用秒表类

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



Answer 8:

也许,你可以写一个这样的方法:

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

并使用它像:

Time(()=>
{
 CallOfTheMethodIWantToMeasure();
});


Answer 9:

我检查,并与所有建议表示赞同。 但想分享的执行时间记录器,我们不希望实现秒表逻辑多次,但仍想衡量多种方法的执行时间一个通用的实现。

对不落实的通用方式记录的主要原因是 - 方法执行是stopwatch.Start()和stopwatch.Stop(间)也可以,我们的执行作进一步处理后需要方法的结果。

因此,要解决这个问题,我创建了下面的示例性实现的执行时间是不符合实际的方法流混合它单独记录。

public static class Helper
{
    public static T Time<T>(Func<T> method, ILogger log)
    {
        var stopwatch = new Stopwatch();
        stopwatch.Start();
        var result = method();
        stopwatch.Stop();
        log.Info(string.Format("Time Taken For Execution is:{0}", stopwatch.Elapsed.TotalMilliseconds));
        return result;
    }
}

public class Arithmatic
{
    private ILogger _log;
    public Arithmatic(ILogger log)//Inject Dependency
    {
        _log = log;
    }

    public void Calculate(int a, int b)
    {
        try
        {
            Console.WriteLine(Helper.Time(() => AddNumber(a, b), _log));//Return the result and do execution time logging
            Console.WriteLine(Helper.Time(() => SubtractNumber(a, b), _log));//Return the result and do execution time logging
        }
        catch (Exception ex)
        {
            _log.Error(ex.Message, ex);
        }
    }

    private string AddNumber(int a, int b)
    {
        return "Sum is:" + (a + b);
    }

    private string SubtractNumber(int a, int b)
    {
        return "Subtraction is:" + (a - b);
    }
}

public class Log : ILogger
{
    public void Info(string message)
    {
        Console.WriteLine(message);
    }

    public void Error(string message, Exception ex)
    {
        Console.WriteLine("Error Message:" + message, "Stacktrace:" + ex.StackTrace);
    }
}

public interface ILogger
{
    void Info(string message);
    void Error(string message, Exception ex);
}

调用部分:

 static void Main()
 {
    ILogger log = new Log();
    Arithmatic obj = new Arithmatic(log);
    obj.Calculate(10, 3);
    Console.ReadLine();
 }


Answer 10:

记录时间时当前步骤开始处理

DateTime dtStart = DateTime.Now;

//Calculate the total number of milliseconds request took (Timespan = to represent the time interval)-> current - started time stamp ...
//TotalMilliseconds -->Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds.
// to measure how long a function is running 
var result=((TimeSpan)(DateTime.Now - dtStart)).TotalMilliseconds.ToString("#,##0.00") + "ms";


文章来源: How do I measure how long a function is running?