Skip to content

Instantly share code, notes, and snippets.

@marcobraghim
Last active August 26, 2021 20:56
Show Gist options
  • Save marcobraghim/73a82cd61a88b41899e2a44d6697db14 to your computer and use it in GitHub Desktop.
Save marcobraghim/73a82cd61a88b41899e2a44d6697db14 to your computer and use it in GitHub Desktop.
Languages comparison (C, C++, Python, PHP, Dart)

PHP

PHP 7.3.8-1+020190807.43+debian91.gbp7731bf (cli) (built: Aug 7 2019 19:46:25) ( NTS ) Copyright (c) 1997-2018 The PHP Group Zend Engine v3.3.8, Copyright (c) 1998-2018 Zend Technologies with Zend OPcache v7.3.8-1+020190807.43+debian91.gbp7731bf, Copyright (c) 1999-2018, by Zend Technologies

Doesn't need compilation

$ time php fibonacci.php

<?php

/**
 * Calculo fibonacci até 1 milhão
 */

$fibonacci = 1;
$last1 = 0;
$last2 = 1;
for ($i=0; $i < 1000000; $i++) {
    $fibonacci = $last1 + $last2;
    $last1 = $last2;
    $last2 = $fibonacci;
}
print("The End\n");

OUTPUT:

The End

real    0m0,050s
user    0m0,036s
sys     0m0,012s

JAVA

openjdk 11.0.4 2019-07-16 OpenJDK Runtime Environment (build 11.0.4+11-post-Debian-1deb10u1) OpenJDK 64-Bit Server VM (build 11.0.4+11-post-Debian-1deb10u1, mixed mode, sharing)

$ javac Fibonacci.java
$ time java Fibonacci
public class Fibonacci {
    public static void main(String[] args) {
        int fibonacci = 1;
        int last1 = 0;
        int last2 = 1;
        for (int i=0; i < 1000000; i++) {
            fibonacci = last1 + last2;
            last1 = last2;
            last2 = fibonacci;
        }
        System.out.println("The End");
    }
}

OUTPUT:

The End

real    0m0,070s
user    0m0,081s
sys     0m0,020s

C

gcc (Debian 8.3.0-6) 8.3.0 Copyright (C) 2018 Free Software Foundation, Inc.

$ gcc -o fibonacciC fibonacci.c
$ time ./fibonacciC
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
    int fibonacci = 1;
    int last1 = 0;
    int last2 = 1;
    for (int i=0; i < 1000000; i++) {
        fibonacci = last1 + last2;
        last1 = last2;
        last2 = fibonacci;
    }

    printf("The End\n");
    return 0;
}

OUTPUT:

The End

real    0m0,009s
user    0m0,009s
sys     0m0,000s

C++

g++ (Debian 8.3.0-6) 8.3.0 Copyright (C) 2018 Free Software Foundation, Inc.

$ g++ -o fibonacciCPP fibonacci.cpp
$ time ./fibonacciCPP
#include <iostream>
#include <cstdlib>
using namespace std;
int main(int argc, char **argv) {
    int fibonacci = 1;
    int last1 = 0;
    int last2 = 1;
    for (int i=0; i < 1000000; i++) {
        fibonacci = last1 + last2;
        last1 = last2;
        last2 = fibonacci;
    }

    printf("The End\n");
    return 0;
}

OUTPUT:

The End

real    0m0,010s
user    0m0,010s
sys     0m0,000s

PYTHON 2

Python 2.7.16

$ python2 -m py_compile fibonacci.py
$ time python2 fibonacci.pyc
fibonacci = 1
last1 = 0
last2 = 1
theRange = 1000000
for i in range(theRange):
    fibonacci = last1 + last2
    last1 = last2
    last2 = fibonacci

print("The End\n")

OUTPUT:

The End

real    0m12,476s
user    0m12,434s
sys     0m0,040s

PYTHON 3

Python 3.7.3

Does not work with py_compile. Got an error: 'RuntimeError: Bad magic number in .pyc file'

$ time python3 fibonacci.py

Same code as Python2

fibonacci = 1
last1 = 0
last2 = 1
theRange = 1000000
for i in range(theRange):
    fibonacci = last1 + last2
    last1 = last2
    last2 = fibonacci

print("The End\n")

OUTPUT:

The End

real    0m12,752s
user    0m12,704s
sys     0m0,048s

DART

Dart VM version: 2.4.1 (Unknown timestamp) on "linux_x64"

Compiled with dart2aot

$ dart2aot Fibonacci.dart Fibonacci.aot
$ time ./dartaotruntime Fibonacci.aot
void main(List<String> args) {
  int fibonacci = 1;
  int last1 = 0;
  int last2 = 1;
  for (int i=0; i < 1000000; i++) {
      fibonacci = last1 + last2;
      last1 = last2;
      last2 = fibonacci;
  }
  print('The End');
}

OUTPUT:

The End

real    0m0,019s
user    0m0,016s
sys     0m0,004s

My own machine:

         _,met$$$$$gg.           prescott@PeDePano
      ,g$$$$$$$$$$$$$$$P.        OS: Debian 10 buster
    ,g$$P""       """Y$$.".      Kernel: x86_64 Linux 4.19.0-5-amd64
   ,$$P'              `$$$.      Uptime: 2h 37m
  ',$$P       ,ggs.     `$$b:    Packages: 3528
  `d$$'     ,$P"'   .    $$$     Shell: bash
   $$P      d$'     ,    $$P     Resolution: 1600x900
   $$:      $$.   -    ,d$$'     DE: GNOME 
   $$\;      Y$b._   _,d$P'      WM: GNOME Shell
   Y$$.    `.`"Y$$$$P"'          WM Theme: 
   `$$b      "-.__               GTK Theme: Adwaita [GTK2/3]
    `Y$$                         Icon Theme: Adwaita
     `Y$$.                       Font: Cantarell 11
       `$$b.                     CPU: Intel Core i3-2100 @ 4x 3.1GHz [37.0°C]
         `Y$$b.                  GPU: Mesa DRI Intel(R) Sandybridge Desktop 
            `"Y$b._              RAM: 4181MiB / 7823MiB
                `""""
@jklemm
Copy link

jklemm commented Jan 24, 2021

@marcobraghim If you use xrange instead of range python will not allocate memory constructing a 100000 items list fisrt. This will give you a different benchmark.

@Snu22
Copy link

Snu22 commented May 5, 2021

Use este código


from time import time

inicio = time()

def fibonacci(maximo):
elemento_atual, proximo_elemento = 0, 1

while elemento_atual < maximo:
yield elemento_atual

elemento_atual, proximo_elemento = \
    proximo_elemento, elemento_atual + proximo_elemento

if name == 'main':
fibonacci_generator = fibonacci(1000000)

for numero_fibonacci in fibonacci_generator:
print(numero_fibonacci)

fim = time()
print('Fim')
print(f'Tempo de execução => {fim - inicio}')

@wilkerdossantos
Copy link

wilkerdossantos commented Aug 26, 2021

Uma pequena alteração no codigo fez toda diferença. segue:

fibonacci = 1.0
last1 = 0.0
last2 = 1.0
i = 0
 
while i < 100000:
	fibonacci = last1 + last2
	last1 = last2
	last2 = fibonacci
	i += 1

print('The End')

Indiquei que o numero é um float assim além de aumentar o max range o interpretador reserva um espaço de memoria um pouco maior "mesmo que isso seja minimo e bem dinâmico" e não instancio um objeto do tipo range com 1 milhão de posições isso não faz muito sentido. Ao invés de percorrer um iterável com 1 milhão de posições, passo apenas a fazer um loop 1 milhão de vezes, com isso obtive os seguintes resultados:

wilker***@pop-os:~/Documentos/Examples$ time python3 fibonacci.py 
The End

real	0m0,043s
user	0m0,038s
sys	0m0,004s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment