TExcelTAD
Home › Game AI › Field Notes: Performance

Field Notes: Performance

One enemy running A*, ten raycasts and a utility evaluation every frame is free. Forty enemies doing it in the same frame, because a wave just spawned, is a hitch the player feels. These notes are about keeping AI inside a budget, and about the habits that make AI bugs findable. The design side is in Field Notes: Design.

1. Give AI a budget, and measure it

At 60 FPS a frame is 16.6 ms, shared by rendering, physics, animation, audio and gameplay. AI usually gets a slice measured in a millisecond or two, less on low-end hardware. Two rules follow:

  • Profile with named scopes (ProfilerMarker, TRACE_CPUPROFILER_EVENT_SCOPE, Godot's profiler) so "AI" is a line you can watch, not a guess (Debugging AI).
  • Look at the worst frame, not the average. AI cost is spiky: everyone notices the player at once, a wave spawns, a door opens and 30 paths are invalid. Average 0.5 ms with a 9 ms spike is a stutter.

2. Time-slice expensive queries

Path requests, EQS-style queries and line-of-sight batches don't need an answer this frame. Put them in a queue and spend a fixed budget per frame, measured in work units (nodes expanded, rays cast) rather than in requests, because one long path can cost as much as twenty short ones.

csharp · try it yourself
using System;
using System.Collections.Generic;

// A wave of 10 enemies all ask for a path on frame 0. Cost = A* nodes each search will expand.
int[] costs = { 120, 340, 90, 600, 150, 80, 410, 200, 130, 260 };
Console.WriteLine(
quot;unbudgeted: frame 0 expands {Sum(costs)} nodes"); const int budget = 500; // nodes per frame var queue = new Queue<(int id, int left)>(); for (int i = 0; i < costs.Length; i++) queue.Enqueue((i, costs[i])); for (int frame = 0; queue.Count > 0; frame++) { int spent = 0; var done = new List<int>(); while (queue.Count > 0 && spent < budget) { var (id, left) = queue.Dequeue(); int work = Math.Min(left, budget - spent); // a search can pause and resume next frame spent += work; if (work == left) done.Add(id); else { queue.Enqueue((id, left - work)); break; } } Console.WriteLine(
quot;frame {frame}: {spent,3} nodes, finished [{string.Join(", ", done)}]"); } static int Sum(int[] a) { int s = 0; foreach (int x in a) s += x; return s; }
unbudgeted: frame 0 expands 2380 nodes
frame 0: 500 nodes, finished [0, 1]
frame 1: 500 nodes, finished []
frame 2: 500 nodes, finished [4, 5]
frame 3: 500 nodes, finished [7, 8]
frame 4: 380 nodes, finished [2, 3, 6, 9]

The spike becomes a flat cost, and the slowest enemy waits a few frames (well under a tenth of a second at 60 FPS), which nobody notices, especially if it plays a "huh?" reaction while it waits. Note the requeue: a paused search goes to the back of the queue, so one enormous request can't starve the others. Engines do this for you in places: Unreal's EQS manager time-slices queries, and navmesh libraries offer sliced path searches. Your own queries need the same treatment.

3. Stagger and level-of-detail the thinking

Most AI doesn't need to decide every frame. Movement and animation run every frame; decisions run a few times per second. Spread agents over frames so they don't all think on the same one, and think less often when far away or off screen:

csharp · try it yourself
using System;

const int agents = 30, frames = 6;
// Agent i is "near" when i < 8, "mid" when i < 20, else "far".
int Interval(int i) => i < 8 ? 2 : i < 20 ? 3 : 6;      // think every N frames

Console.WriteLine("frame:      " + string.Join(" ", Range(frames, f => 
quot;{f,2}"))); Console.WriteLine("all at 10Hz:" + string.Join(" ", Range(frames, f =>
quot;{(f % 6 == 0 ? agents : 0),2}"))); Console.WriteLine("lod, same: " + string.Join(" ", Range(frames, f =>
quot;{Count(f, i => f % Interval(i) == 0),2}"))); Console.WriteLine("lod+stagger:" + string.Join(" ", Range(frames, f =>
quot;{Count(f, i => (f + i) % Interval(i) == 0),2}"))); static string[] Range(int n, Func<int, string> f) { var r = new string[n]; for (int i = 0; i < n; i++) r[i] = f(i); return r; } static int Count(int frame, Func<int, bool> thinks) { int c = 0; for (int i = 0; i < agents; i++) if (thinks(i)) c++; return c; }
frame:       0  1  2  3  4  5
all at 10Hz:30  0  0  0  0  0
lod, same:  30  0  8 12  8  0
lod+stagger: 9 10 10 10 10  9

Updating everyone every sixth frame produces a 30-agent spike and five idle frames. LOD alone still lines everyone up on frame 0. Offsetting each agent by its index ((frame + i) % interval) spreads the same work evenly. Pick the LOD from what the player can perceive: distance, on-screen or not, and whether the agent is in combat. An enemy fighting the player always gets full rate.

4. Cap and cache line-of-sight

Raycasts for vision are the other big AI cost (Vision Cones). Do the cheap tests first (distance, then the cone's dot product) and cast rays only for what survives. Then:

  • cap rays per frame and round-robin through the agents that need them;
  • cache each result for a short moment (a tenth of a second or two); a target rarely becomes visible and invisible again within that window;
  • for groups, one ray from the squad leader can stand in for nearby members when the result only drives a bark or an alert.

5. Event-driven over polling

Don't ask "can I see the player?" in 40 Updates. Let perception publish events (noticed, lost, heard), let the blackboard notify observers when a key changes, and let behavior trees wait on running tasks. Unreal's trees work this way by design (Unreal: AIController, Behavior Trees & Blackboard). Polling hides cost in every agent; events make it proportional to what actually happens.

6. Make AI bugs reproducible

An AI bug that only happens "sometimes" is usually reproducible in principle. Make it reproducible in practice:

  • Seed every random choice (wander, target selection, utility tie-breaks) from a per-agent seed, and log the seed.
  • Run AI on the fixed timestep, not on variable frame time, so the same inputs give the same decisions.
  • Iterate in a stable order. Iterating a hash set of agents can change order between runs; sort by ID or use lists.
  • Record inputs, and ship a replay or "flight recorder" in development builds. Then a QA report becomes a file you load and watch, with debug drawing on.

7. Debug-draw everything, from day one

Teams that add debug views late spend the saved time and more on guesswork. Every time you add an AI feature, add its debug view in the same change: the path, the cone, the scores, the chosen cover point, the token holder. If you can't see it, you can't tune it, and you can't tell a design problem from a bug.

Test yourself

A wave spawns and 30 enemies request paths in the same frame, causing a hitch. What is the standard fix?

  1. Use a faster CPU
  2. Queue the requests and spend a fixed per-frame budget of work, resuming long searches next frame
  3. Skip pathfinding for half the enemies
  4. Precompute paths for every pair of points

Why offset each agent's update by its index ((frame + i) % interval)?

  1. To make agents smarter
  2. So agents with the same interval don't all think on the same frame
  3. To reduce memory
  4. To keep agents in sync

Which habit most helps reproduce a rare AI bug?

  1. Variable-timestep AI updates
  2. Seeded randomness, fixed-step updates, stable iteration order and recorded inputs
  3. Printing everything to the console
  4. Turning off debug drawing