Benchmarks

Arithmetic and recursion

Task: Let
  fib(1) := 1, fib(2) := 1,
  fib(n) := fib(n-1) + fib(n-2).
Calculate fib(36) naively.
Time Language Compiler, Interpreter Remarks
00.058s C gcc 5.4.0 gcc -O3
00.12s Java HotSpot, OpenJDK 1.8.0
00.18s SML SML/NJ 110.78
00.19s Rust rustc 1.17, LLVM 4.0 rustc -C opt-level=3
00.21s C clang 3.5, LLVM 3.5 clang -Ofast
00.21s SML Poly/ML 5.6
00.22s C gcc 5.4.0 not optimized
00.23s Pascal fpc 3.0.0
00.24s C clang 3.5, LLVM 3.5 clang -O3
00.41s JavaScript node.js 4.2, V8 4.5
03.0s Ruby ruby 2.3.1
03.4s Moss moss, gcc 5.4 2015, gcc -O3
03.6s Lua lua 5.2.4
07.6s Moss moss, rustc 1.33, LLVM 8.0 2019, type safe1
08.4s Python python 2.7
10.3s Scheme guile 1.8.8
10.4s Python python 3.5
13.3s Perl perl 5.22
17min Octave octave 4.0.0
Ubuntu 16.04 LTS, 32 Bit, Linux Kernel 4.4.
Pentium Dual-Core T4400 at 2.20GHz.

Footnotes:

  1. This implementation is (should be) completely type safe, using array bounds checking, Rc<T> and Rc<RefCell<T>>. There are no unsafe blocks in the interpreter kernel.

Source code

C

#include <stdio.h>

int fib(int n){
    return n<3? 1: fib(n-1)+fib(n-2);
}

int main(){
    int i;
    for(i=0; i<100; i++){
        printf("%i\n",fib(36));
    }
    return 0;
}

Rust

fn fib(n: i32) -> i32 {
    if n<3 {1} else {fib(n-1)+fib(n-2)}
}

fn main(){
    for _ in 0..100 {
        println!("{}",fib(36));
    }
}

Standard ML

fun fib n = if n<3 then 1 else fib(n-1)+fib(n-2);

val i = ref 0;
while !i<>100 do
  (print(Int.toString(fib 36)^"\n"); i := !i+1);

Pascal

program pas;

function fib(n: longint): longint;
begin
  if n<3 then
    fib := 1
  else
    fib := fib(n-1)+fib(n-2)
end;

  var i: integer;
begin
  for i:=1 to 10 do
    writeln(fib(36));
end.

Java

public class Fib{
    static int fib(int n){
        return n<3? 1 : fib(n-1)+fib(n-2);
    }
    public static void main(String[] args){
        for(int i=0; i<100; i++){
            System.out.println(fib(36));
        }
    }
}

JavaScript

function fib(n){
    return n<3? 1 : fib(n-1)+fib(n-2);
}

console.log(fib(36));

Ruby

def fib(n)
  if n<3 then 1 else fib(n-1)+fib(n-2) end
end

puts fib(36)

Moss

function fib(n)
  1 if n<3 else fib(n-1)+fib(n-2)
end

print(fib(36))

Lua

function fib(n)
  if n<3 then
    return 1
  else
    return fib(n-1)+fib(n-2)
  end
end

print(fib(36))

Python

def fib(n):
    return 1 if n<3 else fib(n-1)+fib(n-2)

print(fib(36))

Scheme

(define (fib n)
  (if (< n 3) 1 (+ (fib (- n 1)) (fib (- n 2)))))

(display (fib 36))
(newline)

Perl

sub fib {
  # my $n = shift;
  return $_[0]<3? 1 : fib($_[0]-1) + fib($_[0]-2);
}

print fib(36), "\n"

Octave

function y = fib(n)
  if (n<3)
    y = 1;
  else
    y = fib(n-1)+fib(n-2);
  endif
endfunction

disp(fib(36));