递归和迭代的速度性能 - 为什么他们以相同的速度不同的&QUOT都运行;小"号码? [英] Speed performance for recursion and iteration – Why do they both run at the same speed for different "small" numbers?

查看:261
本文介绍了递归和迭代的速度性能 - 为什么他们以相同的速度不同的&QUOT都运行;小"号码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想优化,我有代码。为了做到这一点,我写了这个代码,看看递归迭代对比的效果。代码计数至10至的-n个功率。

I'm trying to optimize code that I have. In order to do that, I wrote this code to see the effect of recursion vs. iteration. The code "counts" to 10-to-the-n'th power.

public Form1()
{
    InitializeComponent();
    Stopwatch sw = new Stopwatch();
    sw.Start();
    recurse(4);
    //iterate(4);
    sw.Stop();
    Text = sw.Elapsed.TotalMilliseconds.ToString();
}

void recurse(int i)
{
    if (i < 1) return;
    for (int x = 0; x < 10; x++) recurse(i - 1);
}

void iterate(int i)
{
    i = (int)System.Math.Pow(10, i);
    for (int x = 0; x < i; x++) ;
}



我得到这个意外的结果:当n为1至4的速度是为递归和迭代约0.5毫秒。 4为1000倍-Instead比1这是我预期的慢。只有更大的数字它开始有一个更直观的速度,迭代也比递归快。

I'm getting this unexpected result: when n is 1 through 4 the speed is around 0.5 ms for both recursion and iteration. -Instead of 4 being 1000 times slower than 1 which is what I expected. Only for greater numbers does it start to have a more intuitive speed, the iteration also being faster than the recursion.

为什么同样的速度10倍,10000倍?

Why the same speed for 10 times as for 10,000 times?

推荐答案

即使你做正确的代码来计算在两种情况下同样的事情,不要在一次运行测试之类的东西。你不会得到正确的结果,除非测试本身至少需要一秒钟。运行一百万次,然后划分的总时间。当你测试,那将只需要一两毫秒的事,你应该确保测试时间足够长,忽略了冷缓存的差异。开始()和.Stop()调用,小GC延迟的时候与此同时,等等。另外,还要确保实际工作时间超过空计数循环更多的时间(即的(多次)递归(X)具有足够高的 X 本身是不相关)

Even if you do correct the code to calculate the same thing in both cases, do not test things like that in one run. You're not going to get a proper result unless the test itself takes at least a second. Run it one million times and then divide the total time. When you're testing something that's going to take only a millisecond or two, you should make sure the test takes long enough to ignore the differences of cold cache, times of .Start() and .Stop() calls, small GC delay in the meantime, etc. Also make sure the actual work takes more time than empty counting loop (that is for(many times) recurse(x) has high enough x that the for itself is not relevant)

您的0.5结果MS在一次运行中或多或少毫无意义在这里。 。此外,如果它是一个即时编译语言,我建议你测试之前调用同一个功能,以确保它已经编译 - 否则它会增加开销

Your result of 0.5ms in a single run is more or less meaningless here. Also if it's a jitted language, I'd recommend calling the same function before testing, to ensure it's already compiled - otherwise it's going to add overhead.

TL; DR - 其他的事情你周围发生的功能开销比你的函数需要执行的时间高。

TL;DR - overhead of other things happening around your function is higher than the time your function takes to execute.

这篇关于递归和迭代的速度性能 - 为什么他们以相同的速度不同的&QUOT都运行;小&QUOT;号码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆