自己的代码明显比其他代码慢

时间:2016-11-17 14:19:41

标签: c#

我编写的代码比我在网上找到的某些代码更慢(超出最大时间),即使在线代码看起来更臃肿。

那么我陷入了什么陷阱,我的代码看起来更清晰,但却以某种方式放慢了速度?

慢(我的):

using System;

public class Program
{   
    public static void Main()
    {
        int countMAX = 0;
        int num = 0;

        for (int i = 2; i <= 1000000; i++)
        {
            int count = 1;

            int temp = i;

            while (temp != 1)
            {
                if(temp % 2 == 0) temp /= 2;
                else temp = temp * 3 + 1;
                count++;
            }

            if(count > countMAX)
            {
                countMAX = count;
                num = i;
            }
        }

        Console.WriteLine("Number: " + num + " Hops: " +countMAX);
    }
}

快速(在线):

using System;

public class Program
{   
    public static void Main()
    {
        const int number = 1000000;

        long sequenceLength = 0;
        long startingNumber = 0;
        long sequence;

        for (int i = 2; i <= number; i++) 
        {
            int length = 1;
            sequence = i;
            while (sequence != 1) 
            {
                if ((sequence % 2) == 0) 
                {
                    sequence = sequence / 2;
                } 
                else 
                {
                    sequence = sequence * 3 + 1;
                }

                length++;
            }

        //Check if sequence is the best solution
            if (length > sequenceLength) 
            {
                sequenceLength = length;
                startingNumber = i;
            }
        }

        Console.WriteLine("Num: " + startingNumber + " Count: " + sequenceLength);
    }
}

我在.NET Fiddle上对其进行了测试,其中my solution收到以下错误

  

致命错误:超出了执行时间限制

并且other solution打印正确的结果

  

Num:837799伯爵:525

他们应该以1:1做同样的事情。有人有想法吗?

1 个答案:

答案 0 :(得分:5)

造成差异的因素似乎是int vs long。我想知道使用int的慢速代码是否会出现溢出错误,导致循环时间过长,并且使用long会导致溢出错误。具体而言,long sequence(快速版)与int temp = i;(慢版)。如果您使用long temp = i;,它就像快速代码一样。

果然,如果我们将代码包装在checked块中,它会在行OverflowException上抛出else temp = temp * 3 + 1;