[python-users] Transpiler
Stefan Drees
stefan at drees.name
So Feb 9 17:10:32 CET 2014
Hallo Dirk,
Am 08.02.14 20:38, schrieb Dirk Hünniger:
> Hallo,
> irgendwie finde ich es ja schön, das Python Code lesbar und kurz ist.
> Ich finde es aber nicht schön, das er so zeit verschwenderisch wird wenn
> man anfängt zu rechnen. ...
ich mag Fibonacci lieber mit Fi(0) = 0, Geschmacksfrage - aber wieso
sollte Python an sich da langsam sein? Ich finde eher den unten
stehenden C++ Code langsam (was vermutlich auch am Algorithmus liegt ;-)
$> python2 -V && time python2 fibonacci_generator_sample.py
Python 2.7.6
102334155
real 0m0.074s
user 0m0.017s
sys 0m0.012s
$> python3 -V && time python3 fibonacci_generator_sample.py
Python 3.3.3
102334155
real 0m0.083s
user 0m0.040s
sys 0m0.010s
Der Beispiel-Code dazu ist unten ... zum Vergleich s.u. auch Timings des
naiven Algorithmus in Python und auf derselben Maschine.
> == Laufzeiten ==
>
> dirk at dirk-HP-Pro-3400-Series-MT:~/yp$ time ./a.out
> 165580141
> real 0m1.338s
> user 0m1.335s
> sys 0m0.004s
> dirk at dirk-HP-Pro-3400-Series-MT:~/yp$ time python3 1.py
> 165580141
>
> real 0m54.272s
> user 0m54.296s
> sys 0m0.012s
>
>
> == Python Code ==
>
> def fib(n):
> if (n==0) or (n==1):
> return 1
> else:
> return fib(n-1)+fib(n-2)
>
> print (fib(40))
So ein Algorithmus wie oberhalb lief auch bei meinem Rechner lang:
real 1m4.648s
user 1m4.462s
sys 0m0.070s
Alternativer Python Code (auch für python v2 :-)
fibonacci_generator_sample.py:
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import print_function
def fibonacci_generator():
a, b = 0, 1
yield a
yield b
while True:
a, b = b, a + b
yield b
def fibonacci(n):
if n < 0:
raise NotImplementedError
for i, fin in enumerate(fibonacci_generator(),
start=0):
if i == n:
return fin
# run time 0.1s (where naive algorithm takes 64s)
print(fibonacci(40))
Schönes Wochenende,
Stefan.
> == C++ Code ==
>
> #include <iostream>
>
> template <typename A>
> A fib(A n)
> {
> if ((n==0) || (n==1)) {
> return 1;
> }
> else {
> return fib(n-1)+fib(n-2);
> }
> }
>
> int main(void)
> {
> std::cout << fib<int>(40);
> return 0;
> }
> ________________________________________
>
> Diese Mail erhalten Sie ueber die Mailingliste python-users der
> Universitaet zu Koeln
> Nachrichten an: python-users at uni-koeln.de
> Abonnement und Benutzereinstellungen:
> https://lists.uni-koeln.de/mailman/listinfo/python-users
> Listenarchiv: https://lists.uni-koeln.de/pipermail/python-users/
>
> pyCologne Homepage: http://pycologne.de/
Mehr Informationen über die Mailingliste python-users