The Runtime

From Space Engineers Wiki
Jump to navigation Jump to search

The Runtime is another property which exists on your script’s base class MyGridProgram, alongside Storage, Me and Echo. This property contains information about the running environment of your script.

Runtime's members

  • TimeSinceLastRun

Gets the game time elapsed since the last time the Main method of this program was run. Use for keeping track of time passing in the simulation.
Real-world things like sim-speed or game being paused are irrelevant for this property as it only cares about time passing in the simulated game world.
This property returns no valid data neither in the constructor nor the Save method.
Also keep in mind that the very first time a script is run each session, this property will be empty (TimeSpan.Zero) since - obviously - there hasn’t been a last run yet.

  • LastRunTimeMs

Gets the time in fractional milliseconds it took to execute the Main method the last time it was run. Use for measuring code execution time.
This method returns no valid data neither in the constructor nor the Save method.

  • CurrentInstructionCount

Gets the current number of significant instructions this run. Use only for debugging.

  • MaxInstructionCount

The limit of significant instructions that can be executed in a single run, including any other programmable blocks invoked directly. Use only for debugging.

What are significant instructions?

A significant instruction is whenever any code block or junction or scope is entered.
For example having an if(value) SomeMethod(); will count as one instruction if the condition passes, then if the method is defined in your code, another instruction when that scope is entered.

The instructions limit exists because the programmable block runs on the main thread it and can't run Main forever. The instructions limit is simply a safeguard against infinite loops.

This has no relevance to performance, therefore you should still strive to get the time it takes to execute your code as low as possible, for context 1ms is very slow.
The entire game has to run 60 ticks per real second, therefore it has 16.667ms to run game logic, network handling, simulate physics, mod code, programmable blocks - all this in sequence (because it's one thread).
Don't forget your program can be used in multiple programmable blocks and the server runs all of them.
If one script takes 1ms to run then 10 PBs using it will use 10ms of the tick budget, and when the total tick time goes over 16.67ms (remember it has to run the game in that time too) it leads to low simspeed.

If you’re even remotely close to this instructions limit, your script is probably doing way too much.
Advanced users can use coroutines to run operations over multiple ticks, but you can also split up the tasks manually.


This tutorial was adapted from the original on Malware's MDK wiki, by the author.