En esta oportunidad veremos las ventajas de utilizar Pl/Python sobre Pl/Pgsql para realizar cálculo matemático pesado, entre ellas rendimiento y la capacidad de realizar cálculos sumamente complejos de una forma más sencilla y contando con todas las librerías de Python para esto.
Ejemplo en Pl/PgSQL
create or replace function plrecursivo ( a integer, iteraciones int, profundidad int ) returns integer
as $$
DECLARE
b integer;
c integer;
inicio time;
fin time;
BEGIN
inicio := localtime;
b = (random()*10)::int;
--raise notice 'Profundidad % Valor Pasado % Generado %', profundidad, a, b;
if profundidad < iteraciones then
BEGIN
select * INTO b FROM plrecursivo(b, iteraciones, profundidad + 1);
EXCEPTION WHEN OTHERS THEN
raise notice 'Máximo Recursivo %', Profundidad;
raise notice '% (%)', SQLSTATE, SQLERRM;
return -1;
END;
end if;
c := a + b;
--raise notice 'Profundidad % Valor Pasado % Valor Retorno %', profundidad, a, c;
if profundidad = 1 THEN
fin := localtime;
raise notice 'inicio % fin %', inicio, fin;
end if;
return c;
END;
$$ language plpgsql;
Ejemplo en Pl/Python
create or replace function pyrecursivo ( iteraciones int ) returns integer
as $$
import random
import sys
import datetime
def suma(a, profundidad):
try:
b = random.randint(1,10)
#plpy.notice('Profundidad', profundidad, 'Valor Recibido', a, 'Valor Generado', b)
if profundidad < iteraciones:
b = suma(b, profundidad + 1)
#plpy.notice('Profundidad', profundidad, 'Retorno', a+b)
return a+b
except Exception as e:
plpy.error(str(e))
return 0
inicio = datetime.datetime.now().strftime('%H:%M:%S.%f')
sys.setrecursionlimit(20000)
a = random.randint(1,10)
plpy.notice('Valor inicial', a)
c = suma(a,1)
fin= datetime.datetime.now().strftime('%H:%M:%S.%f')
plpy.notice('Inicio', inicio, 'Fin', fin)
return c
$$ language plpython3u;
Impactos: 56
Comments are closed