I am not a professional programmer. Technical details of multithreading are bit hard to understand for me.
My program does a CPU intensive data transformation, it also checks whether data within an array is correct or not and reports back. I want to achieve max speed with my i7 CPU.
I am providing very simple representation of my code:
1. Am I doing it right?
2. Why do I sometimes get wrong results saved to array? (I will provide more info on this later) <= Tracked down one very not obvious mistake.
3. Why 4 threads are just slightly faster than 2 threads? Could it be because of "Executes each of the provided actions, possibly in parallel."
My speed results:
By the way, I want my application to halt while it is doing this check, that's the main reason why I chose System.Threading.Tasks.Parallel.Invoke vs New System.Threading.Thread().
My program does a CPU intensive data transformation, it also checks whether data within an array is correct or not and reports back. I want to achieve max speed with my i7 CPU.
I am providing very simple representation of my code:
Code:
Private BigArray(400000000) As Byte
Private Sub btnTH1_Click(sender As Object, e As EventArgs) Handles btnTH1.Click
' One thread
Dim sw As New Stopwatch
sw.Start()
DoMath(0, UBound(BigArray))
sw.Stop()
MsgBox(sw.ElapsedMilliseconds)
End Sub
Private Sub btnTH2_Click(sender As Object, e As EventArgs) Handles btnTH2.Click
' Two threads
Dim sw As New Stopwatch
sw.Start()
System.Threading.Tasks.Parallel.Invoke(Sub()
DoMath(0, 200000000)
End Sub,
Sub()
DoMath(200000001, 400000000)
End Sub)
sw.Stop()
MsgBox(sw.ElapsedMilliseconds)
End Sub
Private Sub btnTH4_Click(sender As Object, e As EventArgs) Handles btnTH4.Click
' Four threads
Dim sw As New Stopwatch
sw.Start()
System.Threading.Tasks.Parallel.Invoke(Sub()
DoMath(0, 100000000)
End Sub,
Sub()
DoMath(100000001, 200000000)
End Sub,
Sub()
DoMath(200000001, 300000000)
End Sub,
Sub()
DoMath(300000001, 400000000)
End Sub)
sw.Stop()
MsgBox(sw.ElapsedMilliseconds)
End Sub
Private Function DoMath(ByVal indxS As Long, ByVal indxE As Long) As Boolean
Dim i As Long
For i = indxS To indxE
BigArray(i) = i Mod 256 ' Here I have CPU intensive stuff
Next
Return True ' My original function returns True if no errors were found and vice versa
End Function2. Why do I sometimes get wrong results saved to array? (I will provide more info on this later) <= Tracked down one very not obvious mistake.
3. Why 4 threads are just slightly faster than 2 threads? Could it be because of "Executes each of the provided actions, possibly in parallel."
My speed results:
Code:
1 Thread(s): 5110 ms; 4950 ms; 4912 ms; 4926 ms; 5056 ms
2 Thread(s): 3207 ms; 3153 ms; 3253 ms; 3345 ms; 3173 ms
3 Thread(s): 2849 ms; 2887 ms; 2867 ms; 2899 ms; 2864 ms
4 Thread(s): 2756 ms; 2873 ms; 2793 ms; 2885 ms; 2744 ms