我正在尝试尽可能快地增加数组。将有非常大的阵列,乘以很多次。我有以下代码使用嵌套循环,有没有更快的方法这样做?我有数组a()和b(),我想使sum(1)= a(1)* b(1)+ a(1)* b(2)+ a(1)* b(3)等。
目前我在Excel VBA中,但我很快就会转换为VBA.NET。这比在excel vba中运行它要快多少?我可以使用.Net中更快的方法吗?
Sub Test()
' Just creating the arrays
Dim a() as Integer, b() as Integer, sum() as Integer, i as Integer, j as Integer
ReDim a(1 to 3)
ReDim b(1 to 3)
ReDim sum(1 to 3)
For i = 1 to 3
a(i) = 2 * i
b(i) = 3 * i
Next i
' This is my code I am interested in
For i = 1 to 3
For j = 1 to 3
sum(i) = sum(i) + a(i) * b(j)
Next j
Next i
答案 0 :(得分:2)
除非您的示例过度简化,否则您可以通过总结b()
值来删除内部循环,因为
a*p + a*q + a*r + ... + a*z
相当于
a * (p+q+r+...+z)
所以:
Sub Test()
Dim a(), b(), sum(), i As Long, j As Long, tmp, t, n As Long, tmp2
ReDim a(1 To 20000)
ReDim b(1 To 50)
ReDim sum(1 To 20000)
For i = 1 To 20000
a(i) = i / 100
Next i
tmp2 = 0
For i = 1 To 50
b(i) = i / 100
tmp2 = tmp2 + b(i)
Next i
t = Timer
For n = 1 To 100
For i = 1 To 20000
For j = 1 To 50
sum(i) = sum(i) + a(i) * b(j)
Next j
Next i
Next n
Debug.Print Timer - t ' ~5.5sec
ReDim sum(1 To 20000)
t = Timer
For n = 1 To 100
For i = 1 To 20000
sum(i) = a(i) * tmp2
Next i
Next n
Debug.Print Timer - t ' ~ 0.1 sec
End Sub
答案 1 :(得分:1)
这应该更快:
' This is my code I am interested in
For i = 1 to 3
ai = a(i)
sumi = 0#
For j = 1 to 3
sumi = sumi + ai * b(j)
Next j
sum(i) = sumi
Next i
减少查找数组变量的次数应该可以改善现状,因为现代处理器需要花费更长的时间来从内存中读取数值。我也会考虑loop unrolling,但您必须使用高性能计时器进行测试,看看它是否有帮助。