【问题标题】:Find execution time of recursive function [closed]查找递归函数的执行时间
【发布时间】:2012-11-17 15:21:03
【问题描述】:

我可以使用秒表来查找代码的执行时间

例子:

timer.Start();
for(int i=0; i<100; i++)
{
    ...
}
timer.Stop();
lTime.Text = timer.Elapsed.TotalMilliseconds.ToString();

但是如果我调用一个使用递归的函数呢?

timer.Start();
recur(a, b);
timer.Stop();
lTime.Text = timer.Elapsed.TotalMilliseconds.ToString();

它的显示执行时间为0。

编辑:这段代码运行良好...我在递归函数中有一个错误...

【问题讨论】:

  • 把你的计时器放到调用你的递归函数的方法中。
  • 不要为此使用Timer - 使用Stopwatch
  • @Oded 我用秒表我刚刚叫定时器
  • 我明白了——只是为了迷惑人,嗯?
  • 您是否可以添加代码以确保您的递归函数是重复的,或者在递归函数的顶部放置一个等待以确保运行需要时间,即System.Threading.Thread.Sleep(1000);

标签: c# function recursion timer stopwatch


【解决方案1】:

以下对我有用:

using System.Diagnostics;

namespace StackOverflow.Demos
{
    class Program
    {
        public static void Main(string[] args) 
        {
            Stopwatch timer = new Stopwatch();
            timer.Start();
            recur(10000, new object());
            timer.Stop();
            Console.WriteLine( timer.Elapsed.TotalMilliseconds.ToString());
            Console.ReadKey();
        }
        private static void recur(int a, object b)
        {
            if (a > 0)
                recur(--a, b);
        }
    }
}

【讨论】:

  • 是的,它确实有效...我的代码只是有一些错误..
  • 不用担心 - 如果您想帮助解决您的代码问题,请在新问题中发布:)。
猜你喜欢
  • 1970-01-01
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
  • 2017-11-26
  • 2011-02-08
  • 1970-01-01
  • 2020-11-13
相关资源
最近更新 更多