Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

NOTEBOOKS TUTORIAL SAGEMATH

Views: 4541

OPTIMIZANDO-CODIGOS-PARA-ALTA-PERFORMANCE

CYTHON

Embora o Python seja uma linguagem conveniente de alto nível, certos cálculos podem ser várias vezes mais rápidos do que em Python se eles forem implementados usando tipos estáticos em uma linguagem compilada. Alguns aspectos do Sage seriam muito lentos se eles fossem escritos inteiramente em Python. Para lidar com isso, o Sage suporta uma “versão” compilada do Python chamada Cython ([Cyt] and [Pyr]). O Cython é simultaneamente similar ao Python e ao C. A maior parte das construções em Python, incluindo “list comprehensions”, expressões condicionais, código como += são permitidos; você também pode importar código que você escreveu em outros módulos em Python. Além disso, você pode declarar variáveis em C arbitrárias, e qualquer chamada de bibliotecas em C pode ser feita diretamente. O código resultante é convertido para C e compilado usando um compilador para C

reset()

Execução da serie de fibonacci para o termo 35

Julia

Python (jupyter) Sage Sage (Cython) C(terminal) Octave(GUI) Scilab(GUI) Maxima(GUI) Matlab
 0.094s  3.302s  5.720s 0.66s 0.034s  322.918s

  60.067

 98.350s  
def fiboR_SG_NORMAL(n): if n < 2: return n else: return fiboR_SG_NORMAL(n-1) + fiboR_SG_NORMAL(n-2)
%time fiboR_SG_NORMAL(35)
9227465 CPU time: 9.19 s, Wall time: 9.45 s
%cython # ao colocar int no parametro passado como valor é produzido uma otimização de código fantástica, pois aproxima do código em C def fiboR_SG_CYTHON(int n): if n < 2: return n else: return fiboR_SG_CYTHON(n-1) + fiboR_SG_CYTHON(n-2)
Defined fiboR_SG_CYTHON
Auto-generated code...
%time fiboR_SG_CYTHON(35)
9227465 CPU time: 0.64 s, Wall time: 0.64 s

Altere o nome do arquivo contendo o codigo python de ".py" para ".spyx" e importe o arquivo ".spyx" e execute

load("fiboR_SG.spyx")
Error in lines 1-1 Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/smc_sagews/sage_server.py", line 947, in execute exec compile(block+'\n', '', 'single') in namespace, locals File "", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/smc_sagews/sage_salvus.py", line 3310, in load exec 'salvus.namespace["%s"] = sage.structure.sage_object.load(*__args, **__kwds)'%t in salvus.namespace, {'__args':other_args, '__kwds':kwds} File "<string>", line 1, in <module> File "sage/structure/sage_object.pyx", line 965, in sage.structure.sage_object.load (/projects/sage/sage-dev/src/build/cythonized/sage/structure/sage_object.c:11164) sage.repl.load.load(filename, globals()) File "/projects/sage/sage-dev/local/lib/python2.7/site-packages/sage/repl/load.py", line 263, in load raise IOError('did not find file %r to load or attach' % filename) IOError: did not find file 'fiboR_SG.spyx' to load or attach
%time fiboR_SG(35)
9227465\renewcommand{\Bold}[1]{\mathbf{#1}}9227465
CPU time: 0.66 s, Wall time: 0.67 s

Outro exemplo

Calcular a integral de: f(x)=x2 f(x) = x^{2}

plot(x^2-x,(x,0,10),figsize=(4, 3),fill=True)
integrate(x^2,x,0,5).n()
41.6666666666667

Integração por metodo do trapezio entre os intervalos 0 a 5 e N = 500000

def integral_NORMAL(fun,a, b, N): s = 0 dx = (b-a)/N for i in range(N): s = s + fun(a+i*dx) return n(s*dx)
%time integral_NORMAL(x^2,0,5,700000)
41.6665773809949
<string>:1: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...) See http://trac.sagemath.org/5930 for details.
CPU time: 38.55 s, Wall time: 38.79 s

Compilando com o Cython

%cython def integral_CYTHON(fun,float a, float b, int N): s = 0 dx = (b-a)/N for i in range(N): s = s + fun(a+i*dx) return (s*dx)
Defined integral_CYTHON
Auto-generated code...
%time integral_CYTHON(x^2,0,5,700000)
41.666577633835004
/usr/local/lib/python2.7/dist-packages/smc_sagews/sage_server.py:957: DeprecationWarning: Substitution using function-call syntax and unnamed arguments is deprecated and will be removed from a future release of Sage; you can use named arguments instead, like EXPR(x=..., y=...) See http://trac.sagemath.org/5930 for details. exec compile(block+'\n', '', 'single') in namespace, locals
CPU time: 27.71 s, Wall time: 28.86 s

Numba