繁体   English   中英

如何在 R 中分析和优化已经快速的代码

[英]How to profile and optimise already fast code in R

我在 R 中有一个 function ,我想对其进行优化。 它是最内层循环的一部分,因此它运行了数百万次,我从分析中知道这个 function 占用了总计算时间的大约 80%。

我一直在使用profvis package 来了解我的代码在哪里运行缓慢,并通过逐步改进 function 的单个调用现在只需不到 10 毫秒即可运行。

但是此时, profvis停止工作,并且没有给出哪些代码行使用时间最多的有用细分。 例如:

func <- function(x){
  x1 <- x ** 2
  x2 <- x * 3
  x3 <- sum(1:x)
  x4 <- x1 + x2 + x3
}
profvis::profvis(func(10))
Error in parse_rprof(prof_output, expr_source) : 
  No parsing data available. Maybe your function was too fast?

他们的替代软件包或方法是否可以很好地分析运行时间少于 10 毫秒的函数?

profvis使用Rprof ,因此您可能想在?Rprof阅读它的限制。

如果一切都失败了,您可以运行小规模实验:更改 function 中的某些内容(例如减少分配数量),然后测量调用 function 的循环的总运行时间。 您的编译器设置有些复杂(请参阅?compiler::compile )。 但是你有一个终极的方法来看看一些改变是否有帮助:运行你的代码(很多次),看看它是否变得更快。

func <- function(x){
  x1 <- x ** 2
  x2 <- x * 3
  x3 <- sum(1:x)
  x4 <- x1 + x2 + x3
}
func2 <- function(x)
  x*x + x*3 + sum(seq_len(x)) 


library("compiler")
ii <- 1:1000000
enableJIT(0) 
system.time(for (i in ii) func (100))
system.time(for (i in ii) func2(100))

enableJIT(3) 
system.time(for (i in ii) func (100))
system.time(for (i in ii) func2(100))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM