Saturday, July 4, 2015

Javascript Backend: timeout syntax


Performance critical games and web applications often need to maintain consistent and high frame rates. In this situation it is better to drop some of the logic update rather than dropping render frames. This way the rendering frame rate can maintain some target like 60fps, while the logic updates at a variable rate.

Ian Webster has an article about a technique he calls Timed Array Processing, which is able to drop logic and maintain consistent a frame rate regardless of the number of objects in the scene. It works by taking the current time, and when looping over the scene objects, it only updates objects while under the time limit. This automatically spreads the logic computation load over multiple frames. This highly useful feature should actually be abstracted to the language syntax level, so it can be used in a clear and consistent way.

Rusthon has a smallish code base written in Python, maintained entirely by me, so it only takes me a few days to add a feature like Timed Processing. The new syntax to mark a block of code for timed processing is: with timeout(ms):, where ms is the time to finish in milliseconds. The Rusthon JavaScript transpiler will insert time checking code after each function-calling-expression and inside for/while-loops within that indented block. Runtime execution of the code block will then suspend if the time limit is reached. This allows the programmer to write scaleable code, and not scrafice readabity or maintainablity.

Rusthon Input

 q = []
 with timeout( 10 ):
  i = 0
  while True:
   q.append( CalcFib(i) )
   i += 1

JavaScript Output

 q = [];
 var __clk__ = (new Date()).getTime();
 while (true) {  /* timeout: 10 */
  i = 0;
  while (true)
  {
   if ( (new Date()).getTime() - __clk__ >= 10 )  { break; }
   q.append(CalcFib(i));
   i ++;
  }
  break; 
 }

The example above computes the Fibonaci series for up to 10 milliseconds, on my laptop it reaches the 28th place in that time, example source code. Timed processing is useful when used together with the sleep builtin and the select statement, see this example for more.

No comments:

Post a Comment