- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
假设有一个函数 coSTLy_function_a(x)
使得:
x
,它就会返回相同的输出;和在这些情况下,我们可以将结果存储在一个临时变量中,然后使用该变量进行这些计算,而不是连续两次使用相同的 x
调用该函数。
现在假设下面的例子中有一些函数(f(x)
、g(x)
和 h(x)
) 调用 coSTLy_function_a(x)
,并且其中一些函数可以相互调用(在下面的示例中,g(x)
和 h(x)
都调用 f(x)
)。在这种情况下,使用上面提到的简单方法仍然会导致使用相同的 x
重复调用 coSTLy_function_a(x)
(参见下面的 OkayVersion
) .我确实找到了一种最小化调用次数的方法,但它很“丑陋”(参见下面的 FastVersion
)。有没有更好的方法来做到这一点?
#Dummy functions representing extremely slow code.
#The goal is to call these costly functions as rarely as possible.
def costly_function_a(x):
print("costly_function_a has been called.")
return x #Dummy operation.
def costly_function_b(x):
print("costly_function_b has been called.")
return 5.*x #Dummy operation.
#Simplest (but slowest) implementation.
class SlowVersion:
def __init__(self,a,b):
self.a = a
self.b = b
def f(self,x): #Dummy operation.
return self.a(x) + 2.*self.a(x)**2
def g(self,x): #Dummy operation.
return self.f(x) + 0.7*self.a(x) + .1*x
def h(self,x): #Dummy operation.
return self.f(x) + 0.5*self.a(x) + self.b(x) + 3.*self.b(x)**2
#Equivalent to SlowVersion, but call the costly functions less often.
class OkayVersion:
def __init__(self,a,b):
self.a = a
self.b = b
def f(self,x): #Same result as SlowVersion.f(x)
a_at_x = self.a(x)
return a_at_x + 2.*a_at_x**2
def g(self,x): #Same result as SlowVersion.g(x)
return self.f(x) + 0.7*self.a(x) + .1*x
def h(self,x): #Same result as SlowVersion.h(x)
a_at_x = self.a(x)
b_at_x = self.b(x)
return self.f(x) + 0.5*a_at_x + b_at_x + 3.*b_at_x**2
#Equivalent to SlowVersion, but calls the costly functions even less often.
#Is this the simplest way to do it? I am aware that this code is highly
#redundant. One could simplify it by defining some factory functions...
class FastVersion:
def __init__(self,a,b):
self.a = a
self.b = b
def f(self, x, _at_x=None): #Same result as SlowVersion.f(x)
if _at_x is None:
_at_x = dict()
if 'a' not in _at_x:
_at_x['a'] = self.a(x)
return _at_x['a'] + 2.*_at_x['a']**2
def g(self, x, _at_x=None): #Same result as SlowVersion.g(x)
if _at_x is None:
_at_x = dict()
if 'a' not in _at_x:
_at_x['a'] = self.a(x)
return self.f(x,_at_x) + 0.7*_at_x['a'] + .1*x
def h(self,x,_at_x=None): #Same result as SlowVersion.h(x)
if _at_x is None:
_at_x = dict()
if 'a' not in _at_x:
_at_x['a'] = self.a(x)
if 'b' not in _at_x:
_at_x['b'] = self.b(x)
return self.f(x,_at_x) + 0.5*_at_x['a'] + _at_x['b'] + 3.*_at_x['b']**2
if __name__ == '__main__':
slow = SlowVersion(costly_function_a,costly_function_b)
print("Using slow version.")
print("f(2.) = " + str(slow.f(2.)))
print("g(2.) = " + str(slow.g(2.)))
print("h(2.) = " + str(slow.h(2.)) + "\n")
okay = OkayVersion(costly_function_a,costly_function_b)
print("Using okay version.")
print("f(2.) = " + str(okay.f(2.)))
print("g(2.) = " + str(okay.g(2.)))
print("h(2.) = " + str(okay.h(2.)) + "\n")
fast = FastVersion(costly_function_a,costly_function_b)
print("Using fast version 'casually'.")
print("f(2.) = " + str(fast.f(2.)))
print("g(2.) = " + str(fast.g(2.)))
print("h(2.) = " + str(fast.h(2.)) + "\n")
print("Using fast version 'optimally'.")
_at_x = dict()
print("f(2.) = " + str(fast.f(2.,_at_x)))
print("g(2.) = " + str(fast.g(2.,_at_x)))
print("h(2.) = " + str(fast.h(2.,_at_x)))
#Of course, one must "clean up" _at_x before using a different x...
这段代码的输出是:
Using slow version.
costly_function_a has been called.
costly_function_a has been called.
f(2.) = 10.0
costly_function_a has been called.
costly_function_a has been called.
costly_function_a has been called.
g(2.) = 11.6
costly_function_a has been called.
costly_function_a has been called.
costly_function_a has been called.
costly_function_b has been called.
costly_function_b has been called.
h(2.) = 321.0
Using okay version.
costly_function_a has been called.
f(2.) = 10.0
costly_function_a has been called.
costly_function_a has been called.
g(2.) = 11.6
costly_function_a has been called.
costly_function_b has been called.
costly_function_a has been called.
h(2.) = 321.0
Using fast version 'casually'.
costly_function_a has been called.
f(2.) = 10.0
costly_function_a has been called.
g(2.) = 11.6
costly_function_a has been called.
costly_function_b has been called.
h(2.) = 321.0
Using fast version 'optimally'.
costly_function_a has been called.
f(2.) = 10.0
g(2.) = 11.6
costly_function_b has been called.
h(2.) = 321.0
请注意,我不想“存储”过去使用的所有 x
值的结果(因为这需要太多内存)。此外,我不希望函数返回 (f,g,h)
形式的元组,因为在某些情况下我只想要 f
(所以有无需评估 coSTLy_function_b
)。
最佳答案
你要找的是LRU缓存;仅缓存最近使用的项目,限制内存使用以平衡调用成本与内存需求。
当您使用不同的 x
值调用昂贵的函数时,最多会缓存多个返回值(每个唯一的 x
值),最近最少的已用缓存结果在缓存已满时丢弃。
从 Python 3.2 开始,标准库带有装饰器实现:@functools.lru_cache()
:
from functools import lru_cache
@lru_cache(16) # cache 16 different `x` return values
def costly_function_a(x):
print("costly_function_a has been called.")
return x #Dummy operation.
@lru_cache(32) # cache 32 different `x` return values
def costly_function_b(x):
print("costly_function_b has been called.")
return 5.*x #Dummy operation.
A backport is available对于早期版本,或选择其他可用的库之一,这些库可以处理 PyPI 上可用的 LRU 缓存。
如果你只需要缓存一个最近的项目,创建你自己的装饰器:
from functools import wraps
def cache_most_recent(func):
cache = [None, None]
@wraps(func)
def wrapper(*args, **kw):
if (args, kw) == cache[0]:
return cache[1]
cache[0] = args, kw
cache[1] = func(*args, **kw)
return cache[1]
return wrapper
@cache_most_recent
def costly_function_a(x):
print("costly_function_a has been called.")
return x #Dummy operation.
@cache_most_recent
def costly_function_b(x):
print("costly_function_b has been called.")
return 5.*x #Dummy operation.
这个更简单的装饰器比功能更强大的 functools.lru_cache()
开销更少。
关于python - 当参数保持不变时,最小化 coSTLy 函数调用的次数(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20435245/
SQLite、Content provider 和 Shared Preference 之间的所有已知区别。 但我想知道什么时候需要根据情况使用 SQLite 或 Content Provider 或
警告:我正在使用一个我无法完全控制的后端,所以我正在努力解决 Backbone 中的一些注意事项,这些注意事项可能在其他地方更好地解决......不幸的是,我别无选择,只能在这里处理它们! 所以,我的
我一整天都在挣扎。我的预输入搜索表达式与远程 json 数据完美配合。但是当我尝试使用相同的 json 数据作为预取数据时,建议为空。点击第一个标志后,我收到预定义消息“无法找到任何内容...”,结果
我正在制作一个模拟 NHL 选秀彩票的程序,其中屏幕右侧应该有一个 JTextField,并且在左侧绘制弹跳的选秀球。我创建了一个名为 Ball 的类,它实现了 Runnable,并在我的主 Draf
这个问题已经有答案了: How can I calculate a time span in Java and format the output? (18 个回答) 已关闭 9 年前。 这是我的代码
我有一个 ASP.NET Web API 应用程序在我的本地 IIS 实例上运行。 Web 应用程序配置有 CORS。我调用的 Web API 方法类似于: [POST("/API/{foo}/{ba
我将用户输入的时间和日期作为: DatePicker dp = (DatePicker) findViewById(R.id.datePicker); TimePicker tp = (TimePic
放宽“邻居”的标准是否足够,或者是否有其他标准行动可以采取? 最佳答案 如果所有相邻解决方案都是 Tabu,则听起来您的 Tabu 列表的大小太长或您的释放策略太严格。一个好的 Tabu 列表长度是
我正在阅读来自 cppreference 的代码示例: #include #include #include #include template void print_queue(T& q)
我快疯了,我试图理解工具提示的行为,但没有成功。 1. 第一个问题是当我尝试通过插件(按钮 1)在点击事件中使用它时 -> 如果您转到 Fiddle,您会在“内容”内看到该函数' 每次点击都会调用该属
我在功能组件中有以下代码: const [ folder, setFolder ] = useState([]); const folderData = useContext(FolderContex
我在使用预签名网址和 AFNetworking 3.0 从 S3 获取图像时遇到问题。我可以使用 NSMutableURLRequest 和 NSURLSession 获取图像,但是当我使用 AFHT
我正在使用 Oracle ojdbc 12 和 Java 8 处理 Oracle UCP 管理器的问题。当 UCP 池启动失败时,我希望关闭它创建的连接。 当池初始化期间遇到 ORA-02391:超过
关闭。此题需要details or clarity 。目前不接受答案。 想要改进这个问题吗?通过 editing this post 添加详细信息并澄清问题. 已关闭 9 年前。 Improve
引用这个plunker: https://plnkr.co/edit/GWsbdDWVvBYNMqyxzlLY?p=preview 我在 styles.css 文件和 src/app.ts 文件中指定
为什么我的条形这么细?我尝试将宽度设置为 1,它们变得非常厚。我不知道还能尝试什么。默认厚度为 0.8,这是应该的样子吗? import matplotlib.pyplot as plt import
当我编写时,查询按预期执行: SELECT id, day2.count - day1.count AS diff FROM day1 NATURAL JOIN day2; 但我真正想要的是右连接。当
我有以下时间数据: 0 08/01/16 13:07:46,335437 1 18/02/16 08:40:40,565575 2 14/01/16 22:2
一些背景知识 -我的 NodeJS 服务器在端口 3001 上运行,我的 React 应用程序在端口 3000 上运行。我在 React 应用程序 package.json 中设置了一个代理来代理对端
我面临着一个愚蠢的问题。我试图在我的 Angular 应用程序中延迟加载我的图像,我已经尝试过这个2: 但是他们都设置了 src attr 而不是 data-src,我在这里遗漏了什么吗?保留 d
我是一名优秀的程序员,十分优秀!