【问题标题】:Python : Functional code speed is faster than pure code speed. Why?Python:函数式代码速度比纯代码速度更快。为什么?
【发布时间】:2020-05-14 17:21:41
【问题描述】:

我正在研究堆算法。 我认为堆算法作为函数会比纯代码慢。 所以我做了一个测试。但我发现函数式代码比纯代码快得多。 我觉得这很奇怪,我也不知道为什么。

enter image description here

import time

def heapify(heap):
    for i in range(1, len(heap)):
        while i != 0:
            root = int((i - 1) / 2)
            if heap[i] < heap[root]:
                tmp = heap[i]
                heap[i] = heap[root]
                heap[root] = tmp
                i = root
            else:
                break
    return heap

heap = [5,2,5,0,11,12,7,8,10] * 10000

a = time.time()
for i in range(1, len(heap)):
    while i != 0:
        root = int((i - 1) / 2)
        if heap[i] < heap[root]:
            tmp = heap[i]
            heap[i] = heap[root]
            heap[root] = tmp
            i = root
        else:
            break
b = time.time()
print("func code time :", b-a)

heap2 = [5,2,5,0,11,12,7,8,10] * 10000
a = time.time()
heap2 = heapify(heap2)
b = time.time()
print("pure code time :", b-a)
print(heap == heap2)

【问题讨论】:

  • 你为什么会这样想?一般来说,局部函数作用域内的代码比完全使用全局作用域的代码要快,因为局部变量查找速度更快。请注意,这不是通常意义上的“功能性”。无论如何,再一次,为什么你期望它在函数内部会变慢?

标签: python heap


【解决方案1】:

在 CPython 中,局部变量查找比全局变量查找更优化,因此将代码放入函数中通常使其运行速度比模块级代码快。

table of timings for common operations 中,您可以看到 read_local 和 write_local 比它们的全局读/写对应物更快。

【讨论】:

  • 一个(非常)长的函数会比一个等效(但短得多)的函数更快,调用多个其他函数来执行其子任务吗?或者更具体地说,短函数(小局部变量池)中的函数调用开销+局部变量查找是否大于具有大变量池的函数中的局部变量查找?还是微不足道?我意识到这可能是一个独立的(部分无关的)问题。
猜你喜欢
  • 1970-01-01
  • 2022-01-19
  • 2017-02-03
  • 2015-09-23
  • 1970-01-01
  • 1970-01-01
  • 2017-02-12
相关资源
最近更新 更多