Throttling.md - Mirroar/hivemind GitHub Wiki

Throttling

Throttling in Hivemind is a core mechanism for managing CPU usage and ensuring that the most important tasks are prioritized, especially when CPU resources are limited. Throttling can delay or skip the execution of processes, creep logic, or other operations to keep the bot within Screeps' CPU and bucket constraints.

How Throttling Works

  • Each process and many operations specify an interval (how often they want to run) and a priority (how important they are).
  • When CPU usage or the bucket is low, Hivemind will automatically increase the effective interval for lower-priority processes, causing them to run less frequently.
  • Critical processes (with PROCESS_PRIORITY_ALWAYS) are only skipped in extreme cases, while low-priority processes are skipped first.
  • Throttling is also used for individual creeps and other operations, not just processes.

Throttling in Code

  • The main throttling logic for processes is handled in the kernel (see src/hivemind.ts).
  • For other operations, the throttle function in src/utils/throttle.ts can be used to decide whether to run a piece of code based on the current CPU bucket and a random offset (to spread out work across ticks):
import {throttle, getThrottleOffset} from 'utils/throttle';

// Get a random offset and store on heap for consistent behavior
const offset = getThrottleOffset();

if (throttle(offset, 2000, 8000)) {
  // Run this code every tick if the bucket is healthy enough
}
  • The hasIntervalPassed method (see src/hivemind.ts) can be used to implement your own throttling for recurring tasks outside of the process system. It checks if enough time has passed since the last run, and applies additional throttling based on CPU usage and bucket:
if (hivemind.hasIntervalPassed(10, lastRunTime, 2000, 8000)) {
  // Run this code every ~10 ticks, but less often if CPU is low
}

Best Practices

  • Use throttling for non-critical or expensive operations to avoid exceeding CPU limits.
  • Prefer higher priorities for essential logic, and lower priorities for optional or background tasks.
  • Use throttle or hasIntervalPassed for custom logic that doesn't fit into the process system.