使用 memoise 预缓存 ggplot2 输出以在 Web 服务中使用
对于某些 Web 服务,我需要尽可能加快 ggplot2 绘图的速度。随着 memoise 的引入,绘图函数会自动引入一些缓存,使得第二个绘图比第一个绘图快得多。然而,我的网络服务每个 R 会话仅绘制 1 个图,因此默认情况下这没有帮助。
我想知道进行预缓存是否明智/可能/有用(例如,在实际请求之前进行一些加载计算),或者将记忆缓存保存/加载到磁盘以进行常见调用+输出。
一个例子:
> library(ggplot2);
> pdf(tempfile());
> system.time(print(qplot(speed, dist, color=speed, data=cars, geom=c("point", "smooth"))));
user system elapsed
0.496 0.008 0.512
> system.time(print(qplot(speed, dist, color=speed, data=cars, geom=c("point", "smooth"))));
user system elapsed
0.312 0.004 0.322
For some web services I need to speed up on demand ggplot2 plots as much as possible. With the introduction of memoise, some caching is automatically introduced on the plotting functions, making the second plot significantly faster than the first one. However my web service only draws 1 plot per R session, so this doesn't help by default.
I was wondering if it would be wise/possible/useful to do precaching (e.g. do some calculations onload, before the actual request), or save/load memoise caches to disk for common calls + output.
An example:
> library(ggplot2);
> pdf(tempfile());
> system.time(print(qplot(speed, dist, color=speed, data=cars, geom=c("point", "smooth"))));
user system elapsed
0.496 0.008 0.512
> system.time(print(qplot(speed, dist, color=speed, data=cars, geom=c("point", "smooth"))));
user system elapsed
0.312 0.004 0.322
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
AFAIK,memoise 包仅支持会话内缓存。如果退出 R 会话,就会丢失缓存。我不确定
cacheSweave
/knitr
模型是否对您的 Web 服务有帮助,但我相信您必须像这两个包一样将缓存结果写入磁盘。如果运行相同的代码(通过 MD5 验证),您只需加载缓存即可。您可以提供一个示例,以便我更好地了解问题。AFAIK, the
memoise
package only supports in-session cache. If you quit an R session, you lose the cache. I'm not sure if thecacheSweave
/knitr
model helps for your web service, but I believe you have to write the cached results in the disk anyway like these two packages. If the same code is run (verify by MD5), you simply load the cache. You might provide an example so I can know the problem better.