Code Optimisation: Difference between revisions

From Bohemia Interactive Community
Jump to navigation Jump to search
(less code : faster code)
Line 21: Line 21:
====Length====
====Length====
If any script or function is longer than around 200-300 lines, then perhaps (not true in all cases by all means) you may need to rethink the structure of the script itself, and whether it is all within scope of the functionality required, and if you could do something cleaner, faster and better.
If any script or function is longer than around 200-300 lines, then perhaps (not true in all cases by all means) you may need to rethink the structure of the script itself, and whether it is all within scope of the functionality required, and if you could do something cleaner, faster and better.
====Fewer statements => faster code====
This may sound too obvious, but... optimise the code by removing redundant statements. The following code examples do the same thing, but the latter is 1.5 times faster:
<code>_arr = [1,2];
_one = _arr [[select]] 0;
_two = _arr [[select]] 1;
_three = _one + _two;
</code>
<code>_arr = [1,2];
_three  = (_arr [[select]] 0) + (_arr [[select]] 1);
</code>


====Conditions====
====Conditions====

Revision as of 00:54, 30 January 2014

Make it work.

No need to worry about making it work at light speed if it doesn't even do what it is supposed to. Focus on getting a working product first.

Make it fast.

Optimisation is everything when running lots of instances, with low delays. However, there is such thing as premature optimisation. Also, avoid excessive cleverness.

"Excessive cleverness is doing something in a really clever way when actually you could have done it in a much more straightforward but slightly less optimal manner. You've probably seen examples of people who construct amazing chains of macros (in C) or bizarre overloading patterns (in C++) which work fine but which you look at an go "wtf"? EC is a variation of premature-optimisation. It's also an act of hubris - programmers doing things because they want to show how clever they are rather than getting the job done." - sbsmac

Written it twice? Put it in a function

Pre-compilation by the game engine can save up 20x the amount of time processing, even if the initial time is slightly lengthened. If you've written it twice, or if there is a kind of loop consistently being compiled (perhaps a script run by execVM), make it into a function (FUNCVAR =compile preprocessfilelinenumbers "filename.sqf")

Preprocessfilelinenumbers

The preprocessFileLineNumbers command remembers what it has done, so loading a file once will load it into memory, therefore if wanted to refrain from using global variables for example, but wanted a function precompiled, but not saved, you could simply use: call compile preprocessfilelinenumbers "file"

Remembering the only loss of performance will be the compile time of the string returned and then the call of the code itself.

Length

If any script or function is longer than around 200-300 lines, then perhaps (not true in all cases by all means) you may need to rethink the structure of the script itself, and whether it is all within scope of the functionality required, and if you could do something cleaner, faster and better.

Fewer statements => faster code

This may sound too obvious, but... optimise the code by removing redundant statements. The following code examples do the same thing, but the latter is 1.5 times faster:

_arr = [1,2]; _one = _arr select 0; _two = _arr select 1; _three = _one + _two;

_arr = [1,2]; _three = (_arr select 0) + (_arr select 1);

Conditions

if (_group knowsAbout vehicle _object > 0 && alive _object && canMove _object && count magazines _object > 0) then { //custom code };

You may expect the engine to stop reading the condition after the group has no knowledge about the object but that's false. The engine will continue evaluating the condition until the end even if any of the previous conditions evaluated false.

if (_group knowsAbout vehicle _object > 0) then { if (alive _object && canMove _object && count magazines _object > 0) then { //custom code }; };

Now the engine will only continue reading the condition after the group has some knowledge about the object. Alternatively you can use lazy evaluation syntax. If normal evaluation syntax is (bool1 .. bool2 .. bool3 .. ...), lazy evaluation syntax is (bool1 .. {bool2} .. {bool3} .. ...). Now let's look at the above example using lazy evaluation:

if (_group knowsAbout _vehicle object > 0 && {alive _object} && {canMove _object} && {count magazines _object > 0}) then { //custom code };

Make it pretty.

Documentation, readability, and all that jazz. Clean code is good code.

If Else If Else If Else ...

If you can't escape this using a switch control structure, then try and rethink the functionality. Especially if only one option is needed to match.

On the other hand switch is slower than if then else. To keep tidiness of the switch and speed of if, use if exitWith combined with call: call { if (cond1) exitWith {//code 1}; if (cond2) exitWith {//code 2}; if (cond3) exitWith {//code 3}; //default code };


if () then {}
is faster than
if () exitWith {}
is faster than
if () then {} else {}
or
if () then [{},{}]

However there is no noticeable difference in speed in the following:

_a = 0; if (true) then {_a = 1}; _a = if (true) then [{1},{0}]; _a = if (true) then {1} else {0};

Constants

Using a hard coded constant more than once? Use preprocessor directives rather than storing it in memory or cluttering your code with numbers. Such as: a = _x + 1.053; b = _y + 1.053;

And

_buffer = 1.053; a = _x + _buffer; b = _y + _buffer;

Becomes: #define BUFFER 1.053 _a = _x + BUFFER; _b = _y + BUFFER; This also allows quick modifying of code; with the obvious loss of dynamics, but in that case it isn't a constant is it.

Loops

These first two loop types are identical in speed (+/- 10%), and are more than 3x as fast the proceeding two loop types.

  • for "_y" from # to # step # do { ... };
  • { ... } foreach [ ... ];

Where as these two loops are much slower, and for maximum performance, avoided.

  • while { expression } do { code };
  • for [{ ... },{ ... },{ ... }] do { ... }

Waituntil can be used when you want something to only run once per frame, which can be handy for limiting scripts that may be resource heavy.

As requested, the method to gain this information was via the CBA_fnc_benchmarkFunction, using around 10000 iterations. It was not tested across different stations, and *may* be subject to change between them (ArmA2 is special remember :P):

fA = { private "_i"; _i = 0; while {_i < 1000} do { _i = _i + 1; private "_t"; _t = "0"; }; };

fB = { for "_i" from 0 to 1000 do { private "_t"; _t = "0"; }; };

This code then performs 10,0000 tests and returns average time taken for the function, measured via diag_ticktime. [fA,[],10000] call CBA_fnc_benchmarkFunction; [fB,[],10000] call CBA_fnc_benchmarkFunction;

10,000 Iterations Limit in Loops

Doesn't exist in scheduled environments, only in non - scheduled (only where the 0.3ms delay does not exist).

Threads

The game runs in a scheduled environment, and there are two ways you can run your code. Scheduled and non scheduled.

Depending on where the scope originates, determines how the code is executed. Scheduled code is subject to delays between reading the script across the engine, and execution times can depend on the load on the system at the time.

Some basic examples:

  • Triggers are inside what we call the 'non-scheduled' environment;
  • All pre-init code executions are without scheduling;
  • FSM conditions are without scheduling;
  • Event handlers (on units and in GUI) are without scheduling;
  • Sqf code which called from sqs-code are without scheduling.

The 3ms run time

A scheduled script runs for exactly 3ms before it is put in suspension to be resumed on the next frame, again for another 3ms and so on until the script is finished. The amount of suspension depends on FPS. At 20 FPS the duration of suspension for example is 50ms.

This means that if scheduled script cannot be completed under 3ms, the execution can stretch for undefined amount of time, subject to engine load, FPS and other non scheduled scripts running at the same time. A while true loop with sleep started in scheduled environment therefore has little chance to follow with exact interval.

Scheduled scripts always start with slight delay, subject to engine load.

When am I creating new threads?

Using the spawn/execVM/exec commands are creating small threads within the scheduler for ArmA2 (verification from a BIS DEV for specifics is needed here), and as the scheduler works through each one individually, the delay between returning to the start of the schedule to proceed to the next line of your code can be very high (in high load situations, delays of up to a minute can be experienced!).

Obviously this problem is only an issue when your instances are lasting for longer than their execution time, ie spawned loops with sleeps that never end, or last a long time.

Avoid O(n^2)!!

Commonly you may set up foreach foreach's. 'For' example:

{ { ...} foreach [0,0,0]; } foreach [0,0,0];

This example is of the order (n^2) (3^2 = 9 iterations). For arrays that are twice as big, you will run 4 times slower, and for arrays that are 3 times as big you will run 9 times slower! Of course, you don't always have a choice, and if one (or both) of the arrays is guaranteed to be small it's not really as big of a deal.

Deprecated/Slow Commands

Adding elements to an array

_a set [count _a,_v]

Instead of: _a = _a + [_v]

Removing elements from an array

When FIFO removing elements from an array, the set removal method works best, even if it makes a copy of the new array.

ARRAYX set [0, objnull]; ARRAYX = ARRAYX - [objnull];

Comparing arrays

You cannot compare an array to an array simply by _array1 = [1,2,3]; _array2 = [1,2,3]; if (_array1 == _array2)...WRONG WAY!!!! This will result in error. The fastest way is to subtract one array from another, if the resulting array is [], both arrays contained same values.

_array1 = [1, true, "lol"]; _array2 = ["lol", true, 1]; hint str (count (_array1 - _array2) == 0); //true

Be aware that this method would also return [] if _array1 was ["lol", true, 1, 1, "lol", true]; So making sure arrays are the same length would help. Otherwise use the method below.

Multi-dimensional arrays cannot be as easily subtracted from one another but you can compare these arrays as strings. In this case they have to be identical both in form and value. This method is almost 10 times slower than subtraction method.

_array1 = [1, ["lol", false]]; _array2 = [1, ["lol", false]]; hint str (str _array1 == str _array2); //true

CreateVehicle Array

It is highly recommended to use a standard of createVehicle array rather than the older (deprecated version) createVehicle. It is up to 500x faster than its older brother.

Measuring Velocity Scalar

Sure we can just use Pythagorean theorem to calculate the magnitude from a velocity vector, but a command native to the engine runs much faster (over 10x faster) than the math.

  • VECTOR distance [0,0,0]

Works for 2D vectors as well.

Getting object positions

If your feeling self-conscious and want an AGL solution (ie identical to that of getPos): private "_pos" _pos = getposATL player; if(surfaceIsWater _pos) then { _pos = getposASL player; };

It is still 25% faster than its getPos twin.

nearEntities vs nearestObjects

If a range was set to more thean 100 meters it is highly recommend to use nearEntities instead of nearestObjects.

Note: nearEntities only searches for objects which are alive. Killed units, destroyed vehicles, static objects and buildings will be ignored by the nearEntities command.

forEach vs count

  • Both commands will step through supplied array of elements one by one and both commands will contain reference to current element in _x variable. However count loop is a little faster than forEach loop, but it does not have _forEachIndex variable.

{diag_log _x} count [1,2,3,4,5,6,7,8,9]; //is faster than {diag_log _x} forEach [1,2,3,4,5,6,7,8,9];

_someoneIsNear = {_x distance [0,0,0] < 1000} count allUnits > 0; //is still faster than _someoneIsNear = { if (_x distance [0,0,0] < 1000) exitWith {true}; false } forEach allUnits;

How to test and gain this information yourself?

There is a few ways to measure the information and run time durations inside ArmA2, mostly using differencing of the time itself. The CBA package includes a function for you to test yourself, however if you are remaining addon free or cannot use this, the following code setup is as effective; and allows different ways to retrieve the information (chat text, rpt file, clipboard)

_fnc_dump = { player globalchat str _this; diag_log str _this; //copytoclipboard str _this; }; _t1 = diag_tickTime; // ... code to test (diag_tickTime - _t1) call _fnc_dump;

In ArmA 3 you can simply use in-built library function BIS_fnc_codePerformance.