1
\$\begingroup\$

For my enemy AI, I only need decision making to be done every second or every half second. Would it make a meaningful difference if I didn't run the analyzing method in the Update, but rather invoked a SlowUpdate every second?

\$\endgroup\$
  • 5
    \$\begingroup\$ Did you have any performance issues with this? Or are you just over-optimizing something before it is even an issue? \$\endgroup\$ – Oliver Schöning Feb 15 '14 at 12:45
  • \$\begingroup\$ I have just started so there is nothing to really give performance issues. I just feel that its so unnescesary to do something 40 times per second when i only want it done once a second. Is this bad thinking? \$\endgroup\$ – Daarwin Feb 15 '14 at 12:47
  • 1
    \$\begingroup\$ It depends entirely on your game. Just be careful not to try and do micro-optimizations. I have wasted hours on end reading SO answers on "Is a for...loop faster than a while...loop". It is not a bad idea to reduce the loop iterations, if it has no impact on the game. But if you end up having to write a lot more code just to reduce the AI, then I would leave it until it becomes an issue. \$\endgroup\$ – Oliver Schöning Feb 15 '14 at 13:28
2
\$\begingroup\$

First and foremost, use a profiler and check what are the processor hogs in your game. Otherwise you are spending time augmenting and optimizing something that will not necessarily improve game performance noticeably.

If you already checked and are sure you wish to optimize AI to run a few times per second then in the abstract theoretical sense, you probably want to allocate 1/30 processor time for the AI to run asynchronously instead of lending it 100% of the processor time for 1/60 of a second. In practice in the pragmatic sense I would consider running the AI of different units in random varying times or breaking down the AI process into chunks or enabling the process to run 1-2 milliseconds, stop and pick up again later. This could be done by checking a timer in some pre-determined checkpoints in the program and if the time is up, storing the current relevant data and returning back to the main loop.

i.e.:

ai_work(){
    load_current_progress_state();
    while(work_left){
        do_a_little_bit_of_work();
        if(check_time_spent() > allotted_time){
            save_current_progress_state();
            return;
        }
    }
    return;
}

Running the code only once every X milliseconds would not necessarily yield the benefit you want because it could theoretically cause spikes in frame times.

\$\endgroup\$
  • \$\begingroup\$ Man! SO MUCH to learn. :P But i get the idea. I will keep it in mind when i see that i really need to optimize and then ill research this technique. Thanks! \$\endgroup\$ – Daarwin Feb 15 '14 at 12:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.