可能重复:
$
我碰到一个有趣的问题,其中我有VB中的代码和C ++中完全相同的代码。我希望C ++自然比VB跑得快一点,但是我得到的正好相反:VB的运行速度是C ++的两倍多。程序遍历从1到2,000,000的所有数字,确定它们是否为素数,并将所有素数加在一起。以下是以下片段:
C++
C ++
C++ output:C ++输出:
And here's the exact same thing, only written in VB这里是完全一样的东西,只写在VB
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 output: 1643 The sum of all the prime numbers below 2000000 is 142913828922我觉得有一些明显的缺点,因为我真的看不到VB比C ++快。任何想法?
I feel like there's something obvious that I'm missing, because I really can't see VB being faster than C++. Any ideas?
推荐答案VB.Net解决方案在循环开始时计算一次平方根,而C ++和C#和Java等等)每次都通过循环计算平方根,因为它们的循环基元定义不同。
The VB.Net solution computes the square root once at the beginning of the loop, while C++ (and C and C# and Java and so on) all compute the square root every time through the loop because their looping primitives are defined differently.
更多推荐
VB.net比C ++快?
发布评论