Analysing code performance
It is a common mistake when trying to optimize any piece of code to go in head first and try to optimize everything possible. The problem with this approach is that everything could be optimized in a computer program, and the task of optimizing itself can be very time-consuming. So before even optimizing a model, it is important to analyse it, in order to know which part has the most impact on the simulation duration and to have precise data on your initial execution time to be able to assess your progression.
Some general concepts and tips before starting​
Randomness​
In GAML, many operators have an (implicit) use of randomness (for example, the one_of operator), and this can, of course, impact the simulation duration. Depending on your case, you may need to set the random generator to a certain seed during the analysis part, to make sure that every time the simulation is run, it will get exactly the same data and operations done, and thus comparisons of execution time are more fair/stable. You can do so by adding this line of code to your experiment or your global:
float seed <- 1.0; // put any number you want apart from 0, which would mean "pick a random (different) seed for every simulation"
In other cases, randomness plays a "real" role in your model, and you may want to take that randomness into account in your optimization. In this case, the right approach would be to repeat the tests for a certain amount of time that you think is reasonable to "neutralize" the effect of randomness and to get an idea of what would be the "average" behaviour, or what could be the extremes.
Randomness exists in GAMA: measures have to be taken over several runs to be meaningful when analysing execution time, as it can have an impact.
Work that grows faster than the model​
When profiling, focus first on operations whose cost grows faster than the number of agents or other input being processed; they are most likely to dominate as a model scales. Compare runs at several input sizes with the same parameters and seed, then use the experiment benchmark to locate the expensive work. Thresholds or changes in workload can also affect timing.
Using GAML to get the duration of some code's execution time​
Analysing a model or a piece of code's performance always comes down to assessing the time it took to do something. To do so, we have a few options in GAML:
- Getting the total duration of the previous cycle
- Processing yourself the elapsed time between two parts of the code using the machine time
- Using GAML statements to "benchmark" a precise piece of code
- Getting a detailed report on every duration of every line of code executed
The duration variable​
The duration variable can be used to get the time that the previous step took to execute. At the first step of the simulation, it will be 0, then at the next step it will be the time that the first step took, etc. It is very useful to easily get an idea of the duration of steps, but if we need to get the duration of the initialization phase, or of some piece of code that is happening inside one step, we will need another tool.
Using gama.machine_time​
The gama.machine_time variable is a more versatile tool, it just returns the current time on the computer running the simulation. Using this, we can process the duration of anything we want in the simulation.
For example, record the time before creating the initial population, then subtract it in the init block. This complete model measures the time spent creating 1,000 agents:
model initialization_timer
global {
float initialization_start <- gama.machine_time;
init {
create worker number: 1000;
write "Initialization took: " + (gama.machine_time - initialization_start) + " ms";
}
}
species worker {}
experiment initialization_timer mode: gui {}
Using the benchmark statement​
In addition to this, GAML provides a statement, benchmark, that could be used to execute code a certain number of times and that will print in the console the minimum, maximum, and average duration of those executions. This could be useful to quickly test different parts of the code or alternative codes one after another. Durations are measured in milliseconds. repeat: defaults to 1 and must be strictly positive;
zero or negative values raise a runtime error. Repetitions execute against the same model state:
changes made by the block are not reset between runs. Executing the code multiple times is a common technique in the code optimization world as it is sometimes necessary to eliminate (or assess) the impact of randomness in the given code (as talked about in the section on randomness) or on the computer: for example maybe some hidden task starts just at the same moment and impacts the performances of 1 execution. Here is an example of the use of the benchmark statement to compare two alternative codes:
int nb_concat <- 100000;
benchmark message: "concatenation standard" repeat: 10 {
string result <- '';
loop times:nb_concat{
result <- result + rnd(0,10);
}
}
benchmark message: "concatenation optimized" repeat:10 {
list<string> content;
loop times:nb_concat{
content <+ string(rnd(0,10));
}
string result <- concatenate(content);
}
and the result in the console would look something like this:
concatenation standard (over 10 iteration(s)): min = 687.640833 ms (iteration #0) | max = 1137.205125 ms (iteration #4) | average = 982.2098748999999ms
concatenation optimized (over 10 iteration(s)): min = 35.088792 ms (iteration #8) | max = 38.443292 ms (iteration #0) | average = 36.3634376ms
Collecting individual durations​
Use returns: to declare a temporary list<float> with one duration per execution, in execution order. The variable is available after the benchmark in the enclosing scope;
do not predeclare it. Even with the default single execution, the result is a list of one float.
benchmark "List construction" repeat: 5 returns: durations console: false {
list<int> values <- [1, 2, 3];
}
float first_duration <- durations[0];
write "Average duration: " + mean(durations) + " ms";
console: defaults to true. Setting it to false suppresses only the benchmark summary:
timing and result collection remain enabled, and output written inside the block is unaffected. Omitting returns: retains the normal summary-only usage. The color: and buffering:
facets concern the console summary, not the captured durations.
See also the bundled Recipes > System > Benchmarking model. This block-level measurement is distinct from experiment-wide profiling below.
Using the benchmark facet of an experiment​
This is a more advanced use, the experiment in GAML has a facet called benchmark which can be turned to true, in that case every executed line of code will be recorded in a csv file along with its number of calls and accumulated execution time.
experiment Benchmarking mode: gui benchmark: true { }
Using GAML to get the memory footprint of a simulation​
GAML provides gama.max_memory and gama.free_memory, both measured in bytes, to inspect Java heap capacity:
gama.max_memoryreturns the maximum heap available to GAMA. It can be changed in the GAMA configuration.gama.free_memoryreturns the remaining heap capacity, calculated from the maximum heap and the currently allocated heap. This is process-wide headroom, not a measurement of memory used by one simulation.
How to proceed in practice​
Having an overview of the model's execution time step by step​
When you want to optimize a model but do not know where to start, a good (and easy to implement) starting point is to check the global shape of execution time during your simulation. For that, the duration of each step is recorded and plotted, to get an idea of what happens during the execution.
To do so, simply add this reflex into your global block:
reflex save_step_duration when: cycle>0 {
save [cycle, duration] to:"durations.csv" format:"csv" rewrite:false;
}
This way, you will have every step duration saved in a csv file that you can analyse later on. Once you have the csv file, you can open it in your favourite spreadsheet to visualise it. From there, there are a few possibilities:
- The durations are always pretty much the same, no big variation
- The durations globally increase during the whole simulation
- The durations have a baseline, but sometimes there are steps that are significantly longer than that baseline
- The durations are chaotic, once low then high, there's no real baseline
Each of these cases calls for a different approach.
Stable duration throughout the simulation​
A stable duration does not mean that the model is already optimized. It means there is little variation from one step to another, so compare representative runs or input sizes and profile the operations that take the most time. See what to pay attention to for common sources of cost.
Step duration increases during the simulation​
That kind of result points toward an increase in the simulation complexity during its lifespan: as the simulation progresses, there are more and more things to process. This is typical of either the number of agents continuously increasing or cumulative data being held and used for processing.
Some steps are significantly longer than the rest​
This means that under certain conditions, your model will execute intensive code that is normally not executed. To find exactly what it is, you can inspect the when facets of your reflexes and the if and loop while: conditions in your reflexes and actions. If those longer steps happen with some form of regularity (for example, every 100 steps), it is very probable that it is linked to some behaviour triggered by time or cycle condition, you can look for every, #now, or cycle keyword use in the code.
Chaotic step durations​
This may be the hardest case to analyse, as the complexity seems to come from a combination of "unstable" things. A good approach here could be to try and isolate different parts of the code. Let's say that your model has two main dynamics that interact together; in that case, what you want to do is to try and analyse each one separately. To do so, you will probably need to recreate two new models, each only containing one of those dynamics. If both dynamics cannot function without the other, you could mimic the other with a very simple functions that, for example, always return the same thing, or returns values that you have already processed in a previous simulation, so it does not cost anything in execution time.
The experiment's benchmark: true facet records statement and operator call counts and execution times in a CSV file when the experiment closes. Use that profile to locate expensive code before changing it; avoid adding timing output to every reflex unless a narrower measurement is needed.
What to pay the most attention to​
- every kind of loop (including the ask statements)
- number of agents and interactions
- accumulating data
- reading and writing files
- big string concatenation
- algorithmic scaling, especially repeated or nested work over growing collections
- network code
- displays/charts
- platform settings