Compiling to C for Speed
Larz compiles a recursive fib to real C with larzscript --emit-c and gcc, then times the exact same program interpreted vs compiled natively.
a recursive fib, interpreted
fib(32) makes millions of recursive calls - exactly where an interpreter's cost shows up most:
fn fib(n) {
if n < 2 {
return n
}
return fib(n - 1) + fib(n - 2)
}
print(fib(32))Output
2178309
the same file, timed both ways
larzscript --emit-c turns that same file into real C source; gcc -O2 compiles it to a native binary. Same answer, timed both ways:
fn fib(n) {
if n < 2 {
return n
}
return fib(n - 1) + fib(n - 2)
}
print(fib(32))Output
time larzscript fib.lz real 0m7.167s time ./fib (--emit-c + gcc -O2) real 0m0.091s both print: 2178309
Every snippet on this page is run through the real larzscript interpreter, not hand-typed โ and the timings above are a real run on larzos.com's own server, not invented numbers: roughly a 78× speedup, same program, same answer.
Related
Lesson 15: Publishing Your Own Packagewriting a package and larzscript pkg publish - the final lesson, right after compiling.→Lesson 13: Testing Your Larzscript Codeassert_eq, assert, and report - what's next after building a CLI tool.→Lesson 4: Functions & Recursionfn and recursion - the exact fib function compiled here, back when it was just an idea.→How Fast Is Larzscript, Really?More real benchmarks, no guessing - the full story behind the speedup shown in this lesson.→Learn Larzscript Cookbook29 short "how to X in Larzscript" recipes once you know the basics.→