python - 为什么嵌套函数比非嵌套函数慢这么多?

标签 python performance testing

我试图在斐波那契函数中包含备忘录字典,因为我正在尝试 pickle 函数。然而,在我的测试中,嵌套函数似乎明显更慢,但只有当我使用内存函数时,我才在其他版本的斐波那契中看到这一点。

我所有的测试:https://gist.github.com/dasickis/4733353

#!/usr/bin/env python

memo = {0: 0, 1: 1}

# Contract: [int > 0] -> [int > 0]
def fibonacci(n):
    """ Return the `x`th number in the fibonacci series. """
    if not n in memo:
        memo[n] = fibonacci(n - 1) + fibonacci(n - 2)
    return memo[n]

#--------------------------#

# Contract: [int > 0] -> [int > 0]
def fibonacci_nested(n):
    memo = {0: 0, 1: 1}

    def fib(n):
        """ Return the `x`th number in the fibonacci series. """
        if not n in memo:
            memo[n] = fib(n - 1) + fib(n - 2)
        return memo[n]

    return fib(n)

#--------------------------#

import timeit
stmt = "assert fib(20) == 6765"

print "fibonacci"
print timeit.timeit(stmt, setup="from __main__ import fibonacci as fib")
print 

print "fibonacci_nested"
print timeit.timeit(stmt, setup="from __main__ import fibonacci_nested as fib")

输出:

fibonacci
0.263559103012

fibonacci_nested
11.4014730453

最佳答案

您不会在运行之间清理 memo 字典,从而在不嵌套不公平优势的情况下提供版本。 timeit 第一次运行 fib 时,它将填充 memo 字典,然后后续运行会重新使用它。

嵌套函数每次都会设置一个新的空memo

关于python - 为什么嵌套函数比非嵌套函数慢这么多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14759176/

相关文章:

python - Selenium:访问被拒绝

java - 将树布局保存到文件中。如何有效实现?

php - Selenium、php、phpUnit、404 错误调用 testComplete() 而不是继续,我该如何停止?

node.js - jest 无限期挂起,不运行任何测试

javascript - Python 编码 - 没有任何作用

python - Python中的 'Attempted relative import beyond top-level package'错误意味着什么?

c# - .NET 4.0 内存映射文件性能

testing - 如何将参数发送到 FactoryGirl 特征?

python - Tensorflow支持在线训练吗?

python - 如何高效地删除 'NaN' 值旁边的值?