21.12.2022 Views

python_para_desenvolvedores_2ed

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Performance 279

"""

Fibonacci calculado por um loop.

"""

if n > 1:

# O dicionário guarda os resultados

fibs = {0:1, 1:1}

for i in xrange(2, n + 1):

fibs[i] = fibs[i - 1] + fibs[i - 2]

return fibs[n]

else:

return 1

print 'fib1'

cProfile.run('[fib1(x) for x in xrange(1, 31)]')

print 'fib2'

cProfile.run('[fib2(x) for x in xrange(1, 31)]')

Saída:

fib1

7049124 function calls (32 primitive calls) in 21.844 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)

1 0.000 0.000 21.844 21.844 <string>:1(<module>)

7049122/30 21.844 0.000 21.844 0.728 fibs.py:4(fib1)

1 0.000 0.000 0.000 0.000 {method 'disable' of

'_lsprof.Profiler' objects}

fib2

32 function calls in 0.001 CPU seconds

Ordered by: standard name

ncalls tottime percall cumtime percall filename:lineno(function)

1 0.000 0.000 0.001 0.001 <string>:1(<module>)

30 0.001 0.000 0.001 0.000 fibs.py:13(fib2)

1 0.000 0.000 0.000 0.000 {method 'disable' of

'_lsprof.Profiler' objects}

A performance do cálculo da série de Fibonacci usando um laço que preenche

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!