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

时间:2012-04-11 13:42:03

标签: c# .net 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();

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

但这并不算什么。为什么呢?

11 个答案:

答案 0 :(得分:49)

为避免将来出现计时器问题,请输入正确的代码:

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

但这是错误的方法。您必须使用Stopwatch (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);

答案 1 :(得分:44)

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

答案 2 :(得分: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

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

答案 3 :(得分: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"));

答案 4 :(得分:11)

Visual Studio 2015,2017专业版和企业版都有诊断工具。如果您在函数末尾有一个断点,它将在 Events 标签下显示时间和持续时间,如图所示:

Enter image description here

您可以查看文章 Diagnostic Tools debugger window in Visual Studio 2015 了解更多详情。

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

答案 5 :(得分:7)

使用System.Diagnostics的Stopwatch

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

答案 6 :(得分:6)

对于功能计时,您应该使用Stopwatch Class

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

答案 7 :(得分:4)

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

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

答案 8 :(得分:2)

我审核并同意所有建议。但是想分享一个执行时间记录器的通用实现,我们不想多次实现秒表逻辑,但仍想测量多种方法的执行时间。

不以通用方式实现记录器的主要原因是 - 方法执行在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();
 }

答案 9 :(得分:1)

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

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

答案 10 :(得分:0)

为了在调试代码时查看断点之间经过的毫秒数,Visual Studio 提供了 PerfTips,它是一个内置、有用且快速的工具。

相关问题