简体   繁体   English

为什么嵌套函数比未嵌套的版本要慢得多?

[英]Why is a nested function so much slower than the unnested version?

I'm trying to contain memo dict inside fibonacci as I'm trying to pickle the function. 我试图在斐波那契内部包含备注字典,因为我想使函数腌制。 However, in my tests, it seems that the nested function is significantly slower, but I don't see this with other versions of fibonacci only when I'm using the memoized function. 但是,在我的测试中,嵌套函数似乎要慢得多,但是只有在使用备注函数时,我才能在其他版本的斐波那契中看到这一点。

All my tests: https://gist.github.com/dasickis/4733353 我所有的测试: 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")

Outputs: 输出:

fibonacci
0.263559103012

fibonacci_nested
11.4014730453

You don't clean the memo dictionary between runs giving the version without nesting an unfair advantage. 您不会在两次运行之间清理memo字典,而不会给版本带来嵌套的不公平优势。 The first time timeit runs fib it'll fill the memo dict and then subsequent runs re-use it. 第一次timeit运行fib ,它会填满memo字典,然后随后的运行中重新使用它。

The nested function sets up a new, empty memo each time. 嵌套函数每次都会设置一个新的空memo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM