Next Previous Contents

21. Profiling

21.1 Introduction

This chapter deals with the subject of writing efficient S-Lang code, and using the S-Lang profiler to isolate places in the code that could benefit from optimization.

The most important consideration in writing efficient code is the choice of algorithm. A poorly optimized good algorithm will almost always execute faster than a highly optimized poor algorithm. In choosing an algorithm, it is also important to choose the right data structures for its implementation. As a simple example, consider the task of counting words. Any algorithm would involve a some sort of table with word/number pairs. Such a table could be implemented using a variety of data structures, e.g., as a pair of arrays or lists representing the words and corresponding numbers, as an array of structures, etc. But in this case, the associative array is ideally suited to the task:

   a = Assoc_Type[Int_Type, 0];
   while (get_word (&word))

Note the conciseness of the above code. It is important to appreciate the fact that S-Lang is a byte-compiled interpreter that executes statements much slower than that of a language that compiles to machine code. The overhead of the processing of byte-codes by the interpreter may be used to roughly justify the rule of thumb that the smaller the code is, the faster it will run.

When possible, always take advantage of S-Lang's powerful array facilities. For example, consider the act of clipping an array by setting all values greater than 10 to 10. Rather than coding this as

    n = length(a);
    for (i = 0; i < n; i++)
      if (a[i] > 10) a[i] = 10;
it should be written as
    a[where(a>10)] = 10;

Finally, do not overlook the specialized modules that are available for S-Lang.

21.2 Using the profiler

slprof is an executable slsh script that implements a standalone profiler for slsh scripts. The script is essentially a front-end for a set of interpreter hooks defined in a file called, which may be used by any application embedding S-Lang. The use of the profiler will first be demonstrated in the context of slprof, and after that follows a discussion of how to use for other S-Lang applications.

(To be completed...)

Next Previous Contents