[英]Optimize redundant calculations inside a function in Python
Is there a way to perform a block of code only once inside a function (say when you define it) and then every time you call the function the interpreter simply ignores it and uses the results directly?有没有办法在 function 中只执行一次代码块(比如定义它时),然后每次调用 function 时,解释器都会忽略它并直接使用结果?
for example:例如:
import time as t
def foo():
### redundant code execution
t0 = t.time()
arr = ('Apples ' * 10000000).split()
print(t.time() - t0)
###
print(arr[0])
This would be a great feature since the variable is only used inside the function and I don't want it to be accessible from the outside.这将是一个很棒的功能,因为该变量仅在 function 内部使用,我不希望从外部访问它。
Thanks,谢谢,
Here, one idea would be to memoize it.在这里,一个想法是记住它。 Essentially, if a function is pure ( always gives the same output for a set of inputs ), you can save a mapping of input to output, the first time you compute it.
本质上,如果 function 是纯的(对于一组输入,总是给出相同的 output),您可以在第一次计算时保存输入到 output 的映射。
For this, you can implement your own memoizer like the below example from Geeks 4 Geeks.为此,您可以实现自己的记忆器,如下面的 Geeks 4 Geeks 示例。 Original link: https://www.geeksforgeeks.org/memoization-using-decorators-in-python/
原文链接: https://www.geeksforgeeks.org/memoization-using-decorators-in-python/
def memoize_factorial(f):
memory = {}
# This inner function has access to memory
# and 'f'
def inner(num):
if num not in memory:
memory[num] = f(num)
return memory[num]
return inner
@memoize_factorial
def facto(num):
if num == 1:
return 1
else:
return num * facto(num-1)
print(facto(5))
Or you can use existing decorator libraries like the one in the link below.或者您可以使用现有的装饰器库,如以下链接中的那个。
https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Yes.是的。 It can be done using something known as a
closure
.它可以使用称为
closure
的东西来完成。
def foo():
result = None
def inner():
nonlocal result
if result is None:
result = ... # do your calculation here
return result
return inner
foo = foo()
A few more points based on the code in the question.基于问题中的代码还有几点。
time.perf_counter
is a bit more accurate than time.time
time.perf_counter
比time.time
更准确一点('Apples ' * 10000000).split()
is the same as ['Apples'] * 10000000
('Apples ' * 10000000).split()
与['Apples'] * 10000000
相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.