$ git clone https://github.com/gaiusm/examples $ cd examples/c++
if n<=2 then fib(n) = 1 else fib(n) = fib(n-1) + fib(n-2)
c++/fib/fib.cc
#include <cstdio> static const int terms = 12; /* * fibonacci - generate nth term in the classical sequence. * precondition : n > 0 * postcondition: returns the nth term */ static int fibonacci (int n) { if (n <= 2) return 1; else return fibonacci (n-1) + fibonacci (n-2); }
/* * main - first user function executed. * precondition : none. * postcondition: returns 0 (silently). */ int main (int argc, char *argv[]) { printf ("Fibonacci numbers for the first %d are: ", terms); for (int i = 1; i <= terms; i++) printf ("%d ", fibonacci (i)); printf ("\n"); }
$ g++ -O0 -g -Wall fib.cpp
$ gdb ./a.out (gdb) run (gdb) quit
$ valgrind ./a.out
c++/fib/fibspeed.cc
#include <cstdio> static const int terms = 45; /* * fibonacci - generate nth term in the classical sequence. * precondition : n > 0 * postcondition: returns the nth term */ static int fibonacci (int n) { if (n <= 2) return 1; else return fibonacci (n-1) + fibonacci (n-2); }
/* * main - first user function executed. * precondition : none. * postcondition: returns 0 (silently). */ int main (int argc, char *argv[]) { printf ("Fibonacci value for the first %d are: ", terms); printf ("... %d\n", fibonacci (terms)); }
$ g++ -O0 -Wall -g fibspeed.cpp $ time ./a.out Fibonacci value for the first 45 are: ... 1134903170 real 0m15.466s user 0m15.461s sys 0m0.000s
$ g++ -O2 -Wall -g fibspeed.cpp
$ time ./a.out Fibonacci value for the first 45 are: ... 1134903170 real 0m3.143s user 0m3.140s sys 0m0.000s
$ g++ -Wall -S -fverbose-asm -g -O2 fibspeed.cpp -o fibspeed.s $ as -alhnd fibspeed.s > fibspeed.lst
static int fibonacci (int n) { if (n <= 2) return 1; else return fibonacci (n-1) + fibonacci (n-2); }
sum (lower, upper) if lower <= upper then return lower else return lower + sum (lower+1, upper)
#include <cstdio> static const int low = 1; static const int high = 1000000; /* * sum - generate the sum of terms lower..upper. * precondition : lower <= upper. * postcondition: returns the sum of lower..upper. */ static int sum (int lower, int upper) { if (lower == upper) return lower; else return lower + sum (lower + 1, upper); }
/* * main - first user function executed. * precondition : none. * postcondition: returns 0 (silently). */ int main (int argc, char *argv[]) { printf ("Sum of numbers from %d..%d is: ", low, high); printf ("%d\n", sum (low, high)); }
$ g++ -g -O0 sum.cpp $ gdb ./a.out (gdb) run segmentation violation (gdb) quit
$ g++ -g -O3 sum.cpp $ gdb ./a.out (gdb) run (gdb) quit Sum of numbers from 1..1000000 is: 1784293664
$ g++ -Wall -S -fverbose-asm -g -O3 sum.cpp -o sum.s $ as -alhnd sum.s > sum.lst
This document was produced using groff-1.22.