Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”
Below is a simple python implementation:
However, this can be made more efficient, though at the expense of readability. Below it is written in C, and takes advantage of the fact that the Fizz Buzz pattern repeats every 15. This allows for the removal of the conditionals.
This becomes the following assembly code from clang when set to maximum optimization (clang -S fizzbuzz.c -O3).
The compiler has unrolled the loop, pulling out the 6 times the loop would run. Of course the true fastest method would be to simply print FizzBuzz directly as it is only 413 characters, 412 excluding the trailing new line.
Some simple profiling using the time command provides the following representative results.
time python fizzbuzz.py
real 0m0.026s
user 0m0.014s
sys 0m0.009s
time ./fizzbuzz
real 0m0.002s
user 0m0.000s
sys 0m0.002s
A clear speed improvement can be seen. Though this is an apples to oranges comparison as python is an interpreted and c a compiled language.