How to maximize coroutine efficiency?

My coroutine will be searching a game tree to determine the best move. I want the coroutine to search for as long as possible, without exceeding 1/60 second, before yielding. I need some direction in how to manage this.

Related question… In case the frame rate is slower than 60 fps, same question. How can I maximize the search time, without exceeding the frame period, before yielding?

To put it blunt and simple: You can’t. (at least not with 100% reliability)

You can ofc write efficient code, you can optimize your search algorithm and split it up in really really tiny parts. Then after every part you can check the time passed and try to estimate if based on the last few executions you can try to search longer or not.

BUT:

Since you are not working with a real-time capeable system you can never be sure that the next step will actually take lets say 1 ms or if it will take longer this time and need 5 ms instead. Reason for this is that you don’t know how the system that you are on will prioritize your current task against other tasks, how fast your system is in general and how occupied it already is.

It might help if you shared your code (at least the relevant parts if that is possible and not too long). Depending on how your data is structured there might be room for improvements or even the possibility to use multithreading here - even though the latter option is for good reason not recommended in connection with unity.

Thank you for explaining that. I was just using a time-wasting loop to simulate AI thinking time. Now I am ready to start on MCTS code. I will post relevant portions of the code if (when) I run into trouble.