I’ve got a HUGE generic list that a particular function uses. It takes quite a bit of time for the function to go through every item in the list. Because every item is independent from one another (aka: the value of one item doesn’t affect the computation of the other), I thought it’d be a neat idea to use multiple CPU threads to compute that list.
I figured that this is the ideal case for using multiple threads.
So in my for loop:
For (int i = startingPoint; i < endPoint; i++) {
}
I have it set up so that the startingPoint and the endPoint are of the appropriate values so that the total amount of items in the list gets divided and computed by different threads.
0, 1000
1000, 2000
2000, 3000
etc.
1 thread, 2 threads, 3 threads, etc. The code seems to work great and I can see in my computer’s activity monitor that my cores are being used. No errors, no crash.
Here’s the thing, though. CPU load never seem to go above 50% of a particular thread (so, for 3 threads, each of them stay at around 50%). I figured that’d be pretty standard/reasonable behaviour so, as much as I would want to use 100% of my threads, I can shrug that off.
Where it gets odd is that, the more threads I use, it seems to take my computer progressively more time to complete the task. It’s almost as if using 1 or 2 threads is faster than using all 8 on my computer. I can understand the initial step of starting each thread could take some time however, I got a Debug.Log time stamp and they all seem to start at a relatively short time from one another… they just seem to go through the function a lot slower.
Is there something I’m missing? Is this normal? I thought maybe there was a bottleneck with memory but I don’t see it either with my computer’s activity monitor nor with Unity’s Profiler (either that or I apparently don’t know how to read it).
Any thoughts or clarifications would be great as I’m kind of new to the whole multi-threaded thing. Thanks.