Skip to main content
Version: 🚧 Alpha 🚧

Optimizing Models

This page presents options for reducing a model’s memory use or execution time. Use performance analysis tools to profile the model first, then compare changes with the same model, data, GAMA build, runtime settings and hardware. An optimization can help one model and make another slower or less predictable.

[!Note] Performance measurements and charts on this page come from example models and are labeled with a GAMA build identified as 2026-11. The hardware and full runtime configuration are not recorded, so treat the numbers as illustrations rather than expected results. Compare alternatives on the same model, data, GAMA build, runtime settings and hardware.

Scheduling​

For agents that have no scheduled behavior and are only read or changed by other agents, such as cells used as data or background geometry, use schedules: [] to exclude them from automatic scheduling. They remain available to other agents.

grid my_grid height: 100 width: 100 schedules: [] {}

GAMA evaluates the schedules expression when the population is stepped. It can select agents conditionally or vary the selection over time. The Random Scheduler model uses shuffle to vary the execution order of a species at each step:

species scheduler schedules: shuffle(no_scheduler);

In the same way, modelers can use the frequency facet to define when the agents of a species are going to be activated. By setting this facet to 0, the agents are never activated.

species my_species frequency: 0 {}

Performances​

Consider the following model:

global {
int nb_cells <- 1000;
bool is_scheduled <- true;
}

grid my_grid height: nb_cells width: nb_cells schedules: is_scheduled ? my_grid : [] ;

In this example, scheduling one million grid cells took longer per step than leaving the grid unscheduled. The timings are specific to the example setup; measure the target model before applying this change.

Grid​

Optimization Facets​

In this section, we present some facets that allow to optimize the use of grids (in particular in terms of memory). Note that all these facets can be combined (see the Life model from the Models library).

use_regular_agents​

If false, then a special class of agents is used. This special class of agents uses fewer memories but has some limitations: the agents cannot inherit from a "normal" species, they cannot have sub-populations, their name cannot be modified, etc.

grid cell width: 50 height: 50 use_regular_agents: false {}

use_individual_shapes​

If false, then only one geometry is used for all agents. This facet can reduce memory use. Because agents share one geometry, consider whether the model needs individual geometries before disabling them.

grid cell width: 50 height: 50 use_individual_shapes: false {}

Performances​

Consider the following model:

global {
int nb_cells <- 2000;
bool Puse_individual_shapes <- true;
bool Puse_regular_agents <- true;
}


grid my_grid height: nb_cells width: nb_cells
use_individual_shapes: Puse_individual_shapes
use_regular_agents: Puse_regular_agents {
bool active <- false;
}

The table compares memory recorded during creation of four million grid cells for combinations of the two facets. The result depends on the model and runtime configuration; do not treat the percentage difference as a general guarantee.

use_individual_shapesuse_regular_agentsMemory used (MB)
falsefalse3308.38
falsetrue3307.90
truefalse5097.77
true (default)true (default)5073.43

Parallel execution​

The grid statement can also specify whether the agents of the grid are computed in parallel, using the facet parallel. This could increase (depending on the computation) the execution time. For more details about the pros and cons of doing so, please refer to the parallel section.

Use of field instead of grids​

grid provides a simple way to manipulate raster data in an agent-based model using agents. It is also perfect to discretize the environment and provides an easy way to locate and move agents in space. Nevertheless, as each cell is an agent, it can be very memory-consuming to use this approach. To round this issue, field data types have been introduced. A field can be summarized as a spatialized matrix. It could be considered as a great alternative to grid when the agentification of each cell is not so important, e.g., when the grid represents a landscape where cells contain a biomass value of a crop.

Performance (Memory used)​

The table reports memory observed after initialization when creating one, five or ten fields across several dimensions. It also compares those runs with grids containing one attribute. These values describe the example runs only; field and grid memory use depends on dimensions, attributes, runtime and available memory.

Number of Agents1 Field (MB)5 Fields (MB)10 Fields (MB)
2000 * 20003180.223299.003467.11
5000 * 50003340.594103.785066.26
10000 * 100003919.96981.2310823.51
20000 * 200006207.7218417.16More than 32 GB

Performance (time)​

This comparison measures a simple update of grid-cell attributes and field values, with grid parallel execution disabled and enabled. The timing is specific to that update and setup; benchmark the operations used by the target model.

Field update (ms)Grid update, parallel: false (ms)Grid update, parallel: true (ms)
0.0151920670

Operators​

Matrix and field operations​

The Java Vector API speeds up existing element-wise arithmetic on numeric matrices and fields, including +, -, *, /, scalar powers (^), abs, sin and cos. GAML keeps the same expressions; no separate vector type or setting is needed.

GAMA also adds matrix operations that let models express work over whole grids without writing a per-cell loop. Comparing a matrix with a scalar (>, < or =) returns a matrix of 1.0 and 0.0 values. Matrix-valued ifelse selects between values element by element. These operations have vectorized implementations. The shift operator moves a matrix by column and row offsets, filling uncovered cells with zero or wrapping them when requested.

Grid attributes can be read as typed spatial matrices with cell[attribute] and written back with cell[attribute] <- matrix;. The assignment checks that the matrix dimensions match the grid. cell collect expression also produces a matrix while preserving the grid's spatial structure. These grid-to-matrix operations enable a model to combine cell attributes with matrix operations without manually copying every cell.

For example, the matrix version of Game of Life reads a grid attribute into a matrix, counts neighbors with convolution, applies the rules through element-wise comparisons and ifelse, then writes the result back to the grid:

matrix<float> current <- life_cell[grid_value];
matrix<float> neighbors <- convolution(current, kernel);
matrix<float> next_state <- (neighbors = 3.0)
+ ifelse(neighbors = 2.0, current, 0.0);
life_cell[grid_value] <- next_state;

Vectorized execution changes how supported operations are carried out; it requires no change to model syntax. Performance depends on matrix size, operation and runtime. Compare the matrix formulation with the agent-based version using representative data and the same runtime settings before choosing between them.

Operators can express similar results with different work and memory costs. The examples below compare common alternatives; choose by the required behavior, then measure with representative data before relying on a performance difference.

List operators​

first_with​

It is sometimes necessary to randomly select an element of a list that verifies a given condition. Many modelers use the one_of and the where operators to do this:

bug one_big_bug <- one_of (bug where (each.size > 10));

Another way to select a random matching element is to shuffle the list and use first_with to return the first match:

bug one_big_bug <- shuffle(bug) first_with (each.size > 10);
Performance​

The table below records one benchmark with one million bug agents. Its result is workload-specific: shuffling a list and filtering it have different costs, so compare both approaches with the target model.

MethodAverage Time (ms)
one_of450.61
first_with128.48

where / count​

It is quite common to want to count the number of elements of a list or a container that verify a condition. Several options are possible, including:

int n <- length(my_container where (each.size > 10));

or using the dedicated count operator:

int n <- my_container count (each.size > 10);
Performance​

The table below compares both forms for one list-processing benchmark. Use the form that best expresses the operation; rerun the comparison with representative list sizes if its cost matters to the model.

Number of Elementslength / where (avg ms)count (avg ms)
1000.04240.0616
1,0000.35560.3268
10,0004.45324.9113
100,00053.605954.8167
1,000,000614.4510602.4465

Spatial operators​

container of agents in closest_to, at_distance, overlapping, inside​

Several spatial query operators (such as closest_to, at_distance, overlapping, or inside) allow to restrict the agents being queried to a container of agents. For instance, one can write:

agent closest_agent <- a_container_containing_agents closest_to self;

This expression is formally equivalent to :

agent closest_agent <- a_container_containing_agent with_min_of (each distance_to self);

closest_to delegates the search to the current topology and accepts lists, species and combinations of species. Its cost depends on the topology and the container, so compare it with an explicit with_min_of expression for the target model rather than assuming one form is always faster.

The table records ten repetitions for each container size in the example model, which creates one million agents and selects sublists of different sizes. Treat these timings as observations from that workload.

Number of Elementsclosest_to (avg ms)with_min_of / distance_to (avg ms)
10089.650.05
1,00079.300.39
10,0002.904.80
100,00018.2994.85
1,000,000202.151125.64

To find the closest agent in a species population, use the species as the left operand. A species population and list(predator) are different container types, even though both can refer to the species’ agents.

predator closest_predator <- predator with_min_of (each distance_to self);

or

predator closest_predator <- list(predator) closest_to self;

A species population can be used directly as the left operand. The operator also accepts lists and combinations of species; select the form that matches the data already available in the model:

predator closest_predator <- predator closest_to self;

The direct species form avoids explicitly constructing list(predator). The actual performance difference depends on the topology and workload.

Below are the results of the execution of the 3 examples above (in average of 10 repetitions), with different sizes of the population. The model creates N agents of a species and 1 agent of another species. These measurements compare the three expressions for this example; they do not establish a universal performance ranking.

Number of Elementswith_min_of / distance_to (avg ms)list closest_to (avg ms)species closest_to (avg ms)
1000.0160.0170.008
1,0000.1450.0850.006
10,0001.6610.8340.004
100,00023.73812.3930.019
1,000,000554.434310.7860.159

To query agents from two species, the operands can be combined:

agent closest_agent <- (list(predator1) + list(predator2)) closest_to self;

or, more simply:

agent closest_agent <- (predator1 + predator2) closest_to self;

The list form creates an explicit container from the two populations. The closest_to operator accepts a combined species population directly. This avoids writing an explicit concatenated list; benchmark the expressions if the choice affects a large workload.

Below are the results of the execution of the 2 examples above (in average of 10 repetitions), with different sizes of the population. The model creates N/2 agents of each of 2 species and 1 agent of another third species. The table records the results for this example only and should not be generalized to other models or topologies.

Number of Elementsconcat list (avg ms)concat species (avg ms)
1000.0190.010
1,0000.1030.003
10,0001.0660.015
100,00010.7480.041
1,000,000214.7120.252

Accelerate closest_to with a first spatial filtering​

The closest_to operator can sometimes be slow if numerous agents are concerned by this query. If the model only needs agents within a distance, at_distance can filter the candidates before closest_to. This changes the search scope; use a fallback query when the model requires a nearest agent even when the local filter is empty.

For example, to search within a distance of 10 units:

predator1 closest_agent <- (predator1 at_distance 10) closest_to self;

To be sure to find an agent, the modeler can use a test statement:

agent closest_agent <- (predator1 at_distance 10) closest_to self;
if (closest_agent = nil) {closest_agent <- predator1 closest_to self;}

Below are the results of the execution of the 2 examples above (in average of 10 repetitions), with different sizes of the population. The model creates N/2 agents of each of 2 species and 1 agent of another third species. These measurements compare the two forms for this example only. The distance filter is useful only when it preserves the required search behavior and reduces work for the target model.

Number of Elementsfilter β†’ closest_to (avg ms)closest_to on species β†’ filter (avg ms)
1000.010770.00849
1,0000.028440.00227
10,0000.214760.00374
100,0003.6980.02328
1,000,00052.0770.16445

Displays​

shape​

It is quite common to want to display an agent as a circle or a square. A common mistake is to mix up the shape to draw and the geometry of the agent in the model. When only the displayed shape needs to change, keep the agent geometry unchanged and specify the visual shape in its aspect. The shape attribute describes the geometry used by spatial operations.

species bug {
int size <- rnd(100);

aspect circle {
draw circle(2) color: #blue;
}
}

circle vs square / sphere vs cube​

Note that in OpenGL (3D) and Java2D (2D), the two rendering subsystems used in GAMA, creating and drawing a circle geometry is more time consuming than creating and drawing a square (or a rectangle). In the same way, drawing a sphere is more time consuming than drawing a cube. Hence, if you want to optimize your model displays and if the rendering does not explicitly need "rounded" agents, try to use squares/cubes rather than circles/spheres.

OpenGL refresh facets​

In OpenGL display, it is possible to specify that it is not necessary to refresh a layer with the facet refresh. If in a species, the properties used for visualization (location, shape or color) are never modified, you can set refresh to false. Example:

display city_display_opengl renderer: 3d{
species building aspect: base refresh: false;
species road aspect: base refresh: false;
species people aspect: base;
}

Manipulating containers and species​

Manipulating containers (lists, maps etc.) and agents are usually the core of a model and the most critical parts of the code in terms of performances.

parallel​

It is possible to execute the reflexes of agents of a species in parallel threads. This can greatly improve the execution time of a model as by default agents are executed one after another. To activate parallel execution of agents you just need to set the parallel facet of the species (or grid) to true:

species dummy_species parallel:true{

}
grid my_grid parallel:true{

}

[!Note] Parallel execution can change the order in which agents run. Use it only when the model does not depend on a fixed execution order, and compare results as well as runtime after enabling it.

Take for example this model where each cell of a grid has an effect on its neighbouring cells ,here disabling them, each disabled cell will be represented by the red color and enabled cells by the green color:

model parallel

grid my_grid parallel:false width:5 height:5 {

bool to_be_executed <- true;
rgb color <- #green update:to_be_executed ? #green : #red;
reflex cancel_neighbours {
if to_be_executed{
write "I am cell '" + name + "' and my reflexes are executed";
loop c over:neighbors{
c.to_be_executed <- false;
}
}
to_be_executed <- true; // reset for the next cycle
}
}

experiment a {

output{
display main renderer:2d antialias:false{
grid my_grid border:#black;
}

}
}

With parallel set to false (the default) the order of execution of each cell is always the same and can be predicted to yield this display after the first cycle:

A grid displayed after a sequential execution: the checkerboard is perfectly regular, because the cells were scheduled in a predictable order.

But if you change its value to true you can end up with this:

The same grid displayed after a parallel execution: two cells break the checkerboard, because the order in which the agents run is no longer predictable. And it can change every cycle (or not) and there's no way to know in advance how it's going to look.

Iterating over containers​

In gama there are multiple ways of iterating over containers and agents:

  • the ask statement to iterate over agents
  • the loop statement to iterate over anything, with its multiple syntaxes:
    • times iterates a certain number of times
    • over iterates directly over a list
    • from and to provide an index to iterate in a range of values
    • until iterates until a certain condition is met
  • the different container operators (such as collect or where) provide shortcuts for generic list manipulation tasks

In general the specialized operators (see this page in the documentation for the full list) are way more efficient, followed by ask and the loop over, then comes the other loop syntaxes. Use a container operator when it directly expresses the required operation. Use ask or loop when the model needs statement-based control, and benchmark alternatives when performance matters. Here is an example model that showcases the difference in execution time of the different methods to sum the value of a property of all the agents in the simulation:

model accessinglistitems

global{
int nb_agents <- 50000;
}

species b{

int v;

init {
v <- rnd(0, 10);
}
}

experiment e {

parameter "number of agents" var:nb_agents;

reflex fill_list_from_agents {

write "Start benchmarking with " + nb_agents + " agents";

// reset the agents
ask b{
do die();
}
create b number:nb_agents;

int s1 <- 0;
benchmark "sum with loop over" repeat:100{
s1 <- 0;
loop obj over:b{
s1 <- s1 + obj.v;
}
}

int s2 <- 0;
benchmark "sum with loop from to" repeat:100{
int to <- length(b)-1;
s2 <- 0;
loop i from:0 to:to{
s2 <- s2 + b[i].v;
}
}

int s3 <- 0;
benchmark "sum with loop times" repeat:100{
int to <- length(b);
int i <- 0;
s3 <- 0;
loop times:to{
s3 <- s3 + b[i].v;
i <- i + 1;
}
}

int s4 <- 0;
benchmark "sum with ask" repeat:100{
s4 <- 0;
ask b{
s4 <- s4 + v;
}
}

int s5 <- 0;
benchmark "sum with collect" repeat:100{
s5 <- sum(b collect (each.v));
}

// verify that all methods yield the same result
assert s1 = s2;
assert s2 = s3;
assert s3 = s4;
assert s4 = s5;

}
}

Which gives results similar to this:

Bar chart of the duration of five ways of computing the sum of the values of a grid: collect, ask, loop times, loop from to, loop over.

Big string manipulation​

String manipulation, and especially concatenation (adding two strings together) is harmless for performances in normal condition, but once strings become big enough (thousands of characters), every operation becomes extremely costly. Moreover, the execution time of concatenation seem to be an exponential function of the size of the string. Take for example this model:

model stringconcat

experiment test {

reflex concat {
string s;
int nb_concat <- 100;
loop times:nb_concat{
s <- s + rnd(0,10);
}

}
}

We are simply concatenating random digits into a string, ending up with a 100 character string. Increasing nb_concat increases the amount of string data built by repeated concatenation. The runtime depends on the model and environment; use the benchmark below to measure the effect on the target setup. We can modify a bit the model to have a more precise idea of how long it takes, and let's check how long it would take to compute 200 000 and 300 000 concatenations:

model stringconcat

experiment test {


action concatenate_string(int nb){
string s <- '';
loop times:nb{
s <- s + rnd(0,10);
}
}
reflex concat {

benchmark "concatenating 100 000 times" repeat:10 {
do concatenate_string(100000);
}

benchmark "concatenating 200 000 times" repeat:10 {
do concatenate_string(200000);
}

benchmark "concatenating 300 000 times" repeat:10 {
do concatenate_string(300000);
}

}
}

The table records durations for the three input sizes in this example. They illustrate one run configuration and are not expected timings for other systems:

number of concatenations100 000 characters200 000 characters300 000 characters
duration619 ms2563 ms5749 ms

Bar chart of the duration taken to concatenate an increasing number of characters: the cost of simple concatenation grows far faster than the length of the string.

This can be particularly annoying because creating big string is itself a way to optimize outputing data from a model (it is often faster to write a big string once than small strings many times).

To help with string concatenation, it is advised to use the concatenate operator: instead of concatenating many times your text into one string, append each small string into a list of string, and when all the component are collected, merge them only once with the operator. Let's modify the previous model to see how it works:

model stringconcat

experiment test {


action concatenate_string(int nb){
list<string> list_strings <- [];
loop times:nb{
list_strings <+ string(rnd(0,10));
}
string s <- concatenate(list_strings);
}
reflex concat {

benchmark "concatenating 100 000 times" repeat:10 {
do concatenate_string(100000);
}

benchmark "concatenating 200 000 times" repeat:10 {
do concatenate_string(200000);
}

benchmark "concatenating 300 000 times" repeat:10 {
do concatenate_string(300000);
}

}
}

The following table records the results for the same benchmark setup:

number of concatenations100 000 characters200 000 characters300 000 characters
duration15 ms35 ms45 ms

Now let's compare them:

number of concatenations100 000 characters200 000 characters300 000 characters
duration initial approach619 ms2563 ms5749 ms
duration using concatenate15 ms35 ms45 ms

The same experiment comparing simple concatenation with the concatenate operator: 619, 2563 and 5749 milliseconds against 15, 35 and 45.

In this example, collecting pieces and combining them once takes less time than repeated concatenation. Benchmark both forms with the expected string sizes before choosing one for a model.

Threads​

Since GAMA 1.9.1, a new skill has been added to implement threads in agents. The idea is not to give full control of threads to parallelize operations inside the simulation (though this could be achieved too), but to provide a way to communicate with the outside without blocking the execution of your simulation. GAMA simulation running mostly on one thread, having some heavy asynchronous operation running in a separate thread could greatly improve the simulation time, for example you can use threads to push the state of your simulation to an external web API every 10 minutes.

[!Note] Using threads to interact with your simulation could completely break its reproducibility in a similar way as it is explained in the parallel section.