Array Rotation, Timing Tests
March 9, 2018
We have been looking at Section 2.3 of Jon Bentley’s book Programming Pearls in the last two exercises, and have implemented his “juggling” and “block swap” algorithms. Bentley also discusses a third algorithm, which he calls the “reversal” algorithm, and which we implemented several years ago. Bentley goes on to give timing comparisons between the three algorithms.
Your task is to generate timing comparisons similar to Bentley’s, to see what happens with your system, your language and your compiler. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.
I compiled the code with Gambit, added declarations
(declare (standard-bindings)
(extended-bindings)
(block)
(fixnum)
(not safe))
except for
(define (timing rotate vec dist)
(declare (generic))
(let ((start (cpu-time)))
(rotate vec dist)
(- (cpu-time) start)))
and got times
which is closer to Bentley’s results
Here’s a solution in C.
The output times follow the code.
The swapping approach worked fastest of my implementations.
I was able to improve the speed of the juggle approach by using subtraction to calculate the remainder instead of using the modulus operator.
I also added code to validate that my rotation implementations are working correctly.
Output (-O0):
Output (-O2):
My calc_rotate_time function casts the result to a double in the return statement. That should be removed. An earlier implementation was calculating seconds, and the cast to double was there to bypass integer division. Removing the cast to double won’t have a substantive effect on the numbers reported above.