它不是更快 - 它也慢得多。多線程比單線程慢
我有4核心的CPU。
============================================== ====================
Private Sub btn_Singelthreaded_Click(sender As Object, e As EventArgs) Handles btn_Singelthreaded.Click
Dim Num As Long
Dim sw As New Stopwatch
Dim TimeAvrg As Double
For i = 0 To 8
Num = 0
sw.Restart()
Do Until Num > 500000000 '500,000,000
Num += 1
Loop
TimeAvrg += sw.Elapsed.TotalSeconds
'sw.Stop()
Next
Console.WriteLine($"[Singelthreaded] Avrg Time: {TimeAvrg/8}{Environment.NewLine}")
End Sub
Private NumThrd As Long
Private swThrd As New Stopwatch
Private Sub btn_Multithreaded_Click(sender As Object, e As EventArgs) Handles btn_Multithreaded.Click
Dim T1 As New Threading.Thread(AddressOf ForLoop) : T1.Start()
Dim T2 As New Threading.Thread(AddressOf ForLoop) : T2.Start()
Dim T3 As New Threading.Thread(AddressOf ForLoop) : T3.Start()
End Sub
Private Sub ForLoop()
Dim TimeAvrg As Double
For i = 0 To 2
TimeAvrg = 0
NumThrd = 0
swThrd.Start()
Do Until NumThrd > '500,000,000
NumThrd += 1
Loop
TimeAvrg += swThrd.Elapsed.TotalSeconds
'swThrd.Stop()
Next
Console.WriteLine($"[Multithreaded] Avrg Time: {TimeAvrg/3}{Environment.NewLine}")
End Sub
結果: [Singelthreaded] AVRG時間:2.1183545
[多線程] AVRG時間:11.6677879333333
[?我怎麼問一個很好的問題(http://stackoverflow.com/help/how-to-ask) – buhtz