|
直接上代码.....0到10亿的累加操作
使用VBA计算耗费27秒 且计算结果由于使用Variant类型而不准确
下面是VB.NET代码
Imports System.Threading
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sum As Long
Dim t As New Stopwatch
t.Start()
For i As Long = 0 To 1000000000
sum += i
Next
t.Stop()
MsgBox(t.Elapsed.TotalSeconds & vbCrLf & sum)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim t As New Stopwatch
t.Start()
Dim sA As New clsTask(0, 250000000) ‘分为4段任务来完成
Dim sB As New clsTask(250000001, 500000000)
Dim sC As New clsTask(500000001, 750000000)
Dim sD As New clsTask(750000001, 1000000000)
Dim TdA As New Thread(New ThreadStart(AddressOf sA.SumOfNum))
TdA.Start()
Dim TdB As New Thread(New ThreadStart(AddressOf sB.SumOfNum))
TdB.Start()
Dim TdC As New Thread(New ThreadStart(AddressOf sC.SumOfNum))
TdC.Start()
Dim TdD As New Thread(New ThreadStart(AddressOf sD.SumOfNum))
TdD.Start()
TdA.Join() ’阻塞线程,因为需要4个线程的结果才能得出最终结果
TdB.Join()
TdC.Join()
TdD.Join()
t.Stop()
MsgBox(t.Elapsed.TotalSeconds & vbCrLf & sA.r + sB.r + sC.r + sD.r)
End Sub
End Class
Public Class clsTask
Sub New(ByVal st As Long, ByVal ed As Long)
Me.st = st
Me.ed = ed
End Sub
Private st As Long, ed As Long
Public r As Long
Public Function SumOfNum() As Long
r = 0
For i As Long = st To ed
r += i
Next
End Function
End Class
本机测试结果为:单线程4.2秒 多线程2.7秒
拓展:
摆脱VBA中运算时用户界面无响应的问题
Imports System.Threading
Public Class Form1
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim R As New run
Dim T As New Thread(New ThreadStart(AddressOf R.runTask))
T.Start()
Me.Text = "我已经可以响应用户的操作啦!"
End Sub
End Class
Public Class clsTask
Sub New(ByVal st As Long, ByVal ed As Long)
Me.st = st
Me.ed = ed
End Sub
Private st As Long, ed As Long
Public r As Long
Public Function SumOfNum() As Long
r = 0
For i As Long = st To ed
r += i
Next
End Function
End Class
Public Class run
Sub runTask()
Dim t As New Stopwatch
t.Start()
Dim sA As New clsTask(0, 250000000)
Dim sB As New clsTask(250000001, 500000000)
Dim sC As New clsTask(500000001, 750000000)
Dim sD As New clsTask(750000001, 1000000000)
Dim TdA As New Thread(New ThreadStart(AddressOf sA.SumOfNum))
TdA.Start()
Dim TdB As New Thread(New ThreadStart(AddressOf sB.SumOfNum))
TdB.Start()
Dim TdC As New Thread(New ThreadStart(AddressOf sC.SumOfNum))
TdC.Start()
Dim TdD As New Thread(New ThreadStart(AddressOf sD.SumOfNum))
TdD.Start()
TdA.Join()
TdB.Join()
TdC.Join()
TdD.Join()
t.Stop()
MsgBox(t.Elapsed.TotalSeconds & vbCrLf & sA.r + sB.r + sC.r + sD.r)
End Sub
End Class
|
|