Thread Count Detector - Automatically detect number of actors that will run in parallel

This simple module can detect the maximum number of actors that can actually be run in parallel at the same time. Note that this doesn’t necessarily correspond to the number of cores a system has, but rather the number of threads that Roblox gives you for running scripts in parallel.

Usage is very simple:

local ThreadCountDetector = require(script.ThreadCountDetector)
print(ThreadCountDetector.Detect())

This will print the number of threads you can use

The way it works is it repeatedly runs more and more Actors at the same time, each of them taking 0.1 seconds to run. Once it takes more than 0.1 seconds (with a little room for error) to run all the actors, it stops and returns the last number of Actors it ran. The reason this works is because if there are more Actors trying to run than the number of threads, then it will delay the extra actors running until one of the threads is free, which increases the time it takes to run all of them (seen in the last runParellel section).

This can be run both on client and on server, though it probably won’t work if you already have actors running.
It also won’t work if the module script is a descendant of an instance that prevents scripts from running.

8 Likes

I can see this being reliable at times, good work

1 Like

This isn’t always a good strategy.

It’s always a good idea to have more actors than logical cores because it allows the task scheduler to better distribute the task to cores more equally, like if some cores are being used less it can put threads more to them in need. Theres of course a limit to this too, more threads≠better, in fact the opposite can be true

Roblox said a good rule of thumb is to have the amount of actors the same as the amount of logical units. Like if there are 100 NPCs then each should be an actor (it’s easy to do too because actors are models)
Now if you have a workload to split in to multiple threads then the anwser slightly differs, do your own decisions but a little bit more than the amount of logical threads is good

Anyways this module is still very useful and quite clever thank you for making it :wink:

2 Likes

Yes, you’re completely right.

This was my original use case, having a very computationally expensive task that can take minutes to complete, split between several threads. CanvasDraw - A powerful pixel-based graphics engine (Draw pixels, lines, triangles, read image data, and much more!) - #310 by testing34545

1 Like

Yeah its completely fine for that use case
Anyways you have a quite clever implementation for this I didnt even know it was possible to accurately detect the amount of threads props to you

2 Likes