From e0a1715addb8769b7623cd61335baa40ff301b02 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=A9mie=20Astor?= Date: Sat, 8 Aug 2020 12:09:28 +0200 Subject: [PATCH] :book: Document memoization --- docs/README.mdr | 2 +- docs/Reference/Preprocessor.mdr | 49 +++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/docs/README.mdr b/docs/README.mdr index 33785d24..e6d52ebc 100644 --- a/docs/README.mdr +++ b/docs/README.mdr @@ -19,5 +19,5 @@ Here is the piece of code you're waiting for :tada:: * templates (both class and functions) * easy concurrency/async * [lambdas](Reference/Functions/Lambdas.html) - * memoization + * [memoization](Reference/Preprocessor.md#Memoization) * [variadic](Reference/Functions/Variadic.html) functions diff --git a/docs/Reference/Preprocessor.mdr b/docs/Reference/Preprocessor.mdr index e4e9d832..20c34007 100644 --- a/docs/Reference/Preprocessor.mdr +++ b/docs/Reference/Preprocessor.mdr @@ -1 +1,50 @@ # Gwion Preprocessor + +## Memoization + +You can use the `memoize` pragma to enable [memoization](wikipedia.org/wiki/Memoization) on functions: + +### normal version + +@``` fib_recurs.gw +fun int recursive_fib(int n) { + if (n < 2) + return n; + else + return recursive_fib(n - 2) + recursive_fib(n - 1); +} +<<< 40 => recursive_fib >>>; +@``` + +### memoized version + +The syntax of the `memoize` pragma is as follow: +``` cpp +#pragma memoization +``` + +See the memoized version of previous function: +@``` fib_recurs_memoize.gw +#pragma memoize 2 +fun int recursive_fib(int n) { + if (n < 2) + return n; + else + return recursive_fib(n - 2) + recursive_fib(n - 1); +} +<<< 40 => recursive_fib >>>; +@``` + +Under circomstance where memoization is applicable, +such as this one, you can see a *huge* speed-up. + +@hide echo "normal: $(perf stat gwion fib_recurs.gw 2>&1 | grep elapsed)" +@hide echo "memoized: $(perf stat gwion fib_recurs_memoize.gw 2>&1 | grep elapsed)" + +Memoization setting will be active until the end of file +or until it is changed. +Therefor, if you want to disable memoization for subsequent functions, use: +``` cpp +#pragma memoize 0 +``` + -- 2.43.0