Programming and Data Types    

Program 4 -- Tic-Tac-Toe

This program plays a game of tic-tac-toe. It plays the number of rounds indicated by the tries input argument and returns a vector with the results. The first element of the return vector shows the number of wins for player X, the second element shows the wins for player O, and the third element is the number of games that resulted in a tied score.

Operating System
MATLAB 6.1
MATLAB 6.5
Performance Gain
Windows
7.7 sec.
0.9 sec.
x 8.6
Linux
17.9 sec.
1.8 sec.
x 9.9
Solaris
43.9 sec.
7.4 sec.
x 5.9

Try running the program for 10,000 iterations, recording the elapsed time with tic and toc.

What Makes It Faster

Like the previous sample programs, the tictactoe program spends nearly all of its time in the nested for and while loop. It uses only scalar and matrix data types that support MATLAB performance acceleration. It also makes no function calls and does not use function overloading.

In addition, the following factors also speed up program execution.

Logical Operators.   One of the more interesting things about this program is the extended if statement in the middle of the for loop.

This statement has the following characteristics, each of which is a factor in qualifying for performance acceleration:

Short-Circuiting.   One more thing to note about this extended if statement, although not associated with performance acceleration, is that it saves time on some iterations by short-circuiting. Short-circuiting means that the conditional statement may at times be resolved without having to evaluate every part of the expression. For example, if moves is not greater than 4, then the conditions comparing board spaces to player positions do not need to be evaluated, thus saving processing time.


  Program 3b -- Vector Comparison, Vectorized Measuring Performance