gpt4 book ai didi

Python functools 部分效率

转载 作者:IT老高 更新时间:2023-10-28 21:03:15 26 4
gpt4 key购买 nike

我一直在使用 Python,我设置了以下代码情况:

import timeit

setting = """
import functools

def f(a,b,c):
pass

g = functools.partial(f,c=3)
h = functools.partial(f,b=5,c=3)
i = functools.partial(f,a=4,b=5,c=3)
"""

print timeit.timeit('f(4,5,3)', setup = setting, number=100000)
print timeit.timeit('g(4,5)', setup = setting, number=100000)
print timeit.timeit('h(4)', setup = setting, number=100000)
print timeit.timeit('i()', setup = setting, number=100000)

我得到以下结果:

f: 0.181384086609
g: 0.39066195488
h: 0.425783157349
i: 0.391901016235

为什么调用部分函数需要更长的时间?部分函数只是将参数转发给原始函数还是将静态参数映射到整个过程?另外,如果所有参数都是预定义的,那么 Python 中是否有一个函数可以返回填充的函数体,就像函数 i 一样?

最佳答案

Why do the calls to the partial functions take longer?

带有 partial 的代码由于额外的函数调用而花费了大约两倍的时间。函数调用 are expensive:

Function call overhead in Python is relatively high, especially compared with the execution speed of a builtin function.

-

Is the partial function just forwarding the parameters to the original function or is it mapping the static arguments throughout?

据我所知 - 是的,它只是 forwards the arguments to the original function .

-

And also, is there a function in Python to return the body of a function filled in given that all the parameters are predefined, like with function i?

不,我不知道 Python 中有这样的内置函数。但我认为可以做你想做的事,因为函数是可以复制和修改的对象。

这是一个原型(prototype):

import timeit
import types


# http://stackoverflow.com/questions/6527633/how-can-i-make-a-deepcopy-of-a-function-in-python
def copy_func(f, name=None):
return types.FunctionType(f.func_code, f.func_globals, name or f.func_name,
f.func_defaults, f.func_closure)


def f(a, b, c):
return a + b + c


i = copy_func(f, 'i')
i.func_defaults = (4, 5, 3)


print timeit.timeit('f(4,5,3)', setup = 'from __main__ import f', number=100000)
print timeit.timeit('i()', setup = 'from __main__ import i', number=100000)

给出:

0.0257439613342
0.0221881866455

关于Python functools 部分效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17388438/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com