【问题标题】:VB.net faster than C++? [duplicate]VB.net 比 C++ 快? [复制]
【发布时间】:2010-08-09 16:46:43
【问题描述】:

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

我遇到了一个有趣的问题,其中我在 VB.net 中有代码,而在 C++ 中有完全相同的代码。我希望 C++ 的运行速度自然会比 VB.net 快一点,但我却得到了完全相反的结果:VB.net 的运行速度是 C++ 的两倍多。该程序遍历从 1 到 2,000,000 的所有数字,确定它们是否为素数,并将所有素数相加。以下是sn-ps:

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++ 快。有什么想法吗?

【问题讨论】:

  • 这是 Why does C# execute Math.Sqrt() more slowly than VB.NET? 的副本——唯一的区别是 C++ 而不是 C#。
  • 如果您在循环之外计算平方根,您是否发现性能有任何变化?
  • 你是不是在release模式下编译了C++版本?
  • 抱歉,如果我知道这是问题所在,我会简单地查看一下。但是,我从循环中取出了那个小计算,执行时​​间减少到 1.158 =) 非常感谢 - 一旦达到时间阈值,我会在下面接受你的答案。

标签: c++ vb.net optimization


【解决方案1】:

VB.Net 解决方案在循环开始时计算一次平方根,而 C++(以及 C 和 C# 和 Java 等)都在每次循环中计算平方根,因为它们的循环原语定义不同.

【讨论】:

    【解决方案2】:

    你的问题是

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

    不一样

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

    VB.Net 将在开始时评估一次 Math.Sqrt,而 c++ 必须在每次迭代时评估它。同样的问题已经存在于 C# 而不是 c++ 的 stackoverflow 上。

    【讨论】:

    • +1。解决方案应该是在循环以您正在检查的数字的 Sqrt 开始之前创建一个局部变量。这将在两种语言之间进行更公平的比较。
    猜你喜欢
    • 1970-01-01
    • 2018-10-25
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 1970-01-01
    • 2010-10-10
    相关资源
    最近更新 更多