代码之家  ›  专栏  ›  技术社区  ›  AndyPerfect

VB.NET比C++更快?[复制品]

  •  4
  • AndyPerfect  · 技术社区  · 14 年前

    可能重复:
    Why does C# execute Math.Sqrt() more slowly than VB.NET?

    我遇到了一个有趣的问题,我在VB.net有代码,C++中有完全相同的代码。我希望C++比VB.net自然跑得快一点,但我恰恰相反:VB.NET的运行速度是C++的两倍。程序迭代1到2000000之间的所有数字,确定它们是否是素数,并将所有素数相加。以下是一些片段:

    C++

    void problem10(void)
    {   
       clock_t init, final;
       init=clock();
    
       int maxVal = 2000000;
       long long sumOfPrimes = 0;
       for (long i = 2; i < maxVal; i++)
       {
          if (isPrime(i))
          {
             sumOfPrimes+= i;
          }
       }
       final = clock() - init;
       cout << (double)final / ((double)CLOCKS_PER_SEC);
       cout << "The sum of all the prime numbers below " << maxVal << " is " << sumOfPrimes;
    }
    
    bool isPrime(int NumToCheck)
    {
       for (int i = 2; i <= (sqrt((double)NumToCheck)); i++)
       {
          if (NumToCheck % i == 0)
          {
             return false;
          }
       }
       return true;
    }
    

    C++输出:

    3.846The sum of all the prime numbers below 2000000 is 142913828922
    

    这是完全相同的东西,只写在vb.net中

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim watch As New Stopwatch
        watch.Start()
    
        Dim maxVal As Long = 2000000
        Dim sumOfPrimes As Long = 0
        For i As Integer = 2 To maxVal
            If (isPrime(i) = True) Then
                sumOfPrimes += i
            End If
        Next
        watch.Stop()
        Console.WriteLine(watch.ElapsedMilliseconds)
        Console.WriteLine("The sum of all the prime numbers below " & maxVal & " is " & sumOfPrimes)
    End Sub
    
    Function isPrime(ByVal NumToCheck As Integer) As Boolean
        For i As Integer = 2 To (Math.Sqrt(CDbl(NumToCheck)))
            If (NumToCheck Mod i = 0) Then
                Return False
            End If
        Next
        Return True
    End Function
    

    VB输出:

    1643
    The sum of all the prime numbers below 2000000 is 142913828922
    

    我觉得有一些明显的东西我错过了,因为我真的看不到VB.net比C++快。有什么想法吗?

    2 回复  |  直到 14 年前
        1
  •  8
  •   Gabe Timothy Khouri    14 年前

    VB.NET解决方案在循环开始时计算一次平方根,而C++(和C和C ^和Java等)都通过循环来计算平方根,因为它们的循环基元被不同地定义。

        2
  •  6
  •   josefx    14 年前

    你的问题是

    For i As Integer = 2 To (Math.Sqrt(CDbl(NumToCheck)))
    

    与…不同

    for (int i = 2; i <= (sqrt((double)NumToCheck)); i++)
    

    VB.NET将在一开始就对Maq.qRT进行评估,而C++必须每次迭代都对其进行评估。同样的问题已经存在于StAcExobe上,而不是C++。