R-代码优化

本文连接:Profiling R code
原创作者:xshi0001

Let’s solve the problem but let’s not make it worse by guessing. —Gene Kranz, Apollo13 Lead Flight Director.
\texbf{带着策略解决问题,而不是盲目猜测问题的所在}<em>带着策略解决问题,而不是盲目猜测问题的所在</em>

1. system.time()

作用:测试某个函数或者代码块运行时间,实用于已经知道哪一块代码运行问题
返回 pro_time 类对象,包含 user timeelapsed time
区别是:两类时间区别

Elapsed time > user time
system.time(readLines("http://baidu.com"))#花费更多的时间连接网站,而不是cpu处理上

注: memoise 缓存处理包

memoise 是一个非常简单的缓存包,以本地为基础,减少重复计算。当以相同的参数对同一个函数执行第二次计算的时候,可以直接用第一次计算过的结果作为计算结果。主要接口函数有memoizeforget

library(memoise)
func1 <- memoise(function(){
    Sys.sleep(1)
    runif(1)
}
)
system.time(func1())
system.time(func1())#第二次在对这个相同表达式求解不需要话时间
forget(func1) #清除缓存
system.time(func1)

2. Rprof() & summaryRprof()

Rprof()函数用于打印函数的调用关系和cpu的耗时数据,然后通过summaryRprof函数分析数据产生性能报告($by.total$by.self),左后使用profr库中的plot()函数可视化。

实例1:股票数据分析案例

bidpx1<-read.csv(file="000000_0.txt",header=FALSE) #读取数据
#交易日期、交易时间、股票ID、买一价、买一量、卖一价、卖一量。
names(bidpx1)<-c("tradedate","tradetime","securityid",
                 "bidpx1","bidsize1","offerpx1","offersize1")
bidpx1$securityid<-as.factor(bidpx1$securityid) #将彩票id转化成因子
head(bidpx1) #查看前6行
object.size(bidpx1) #查看文件大小
#以股票ID分组计算每小时买一价的平均值和买一量的总量
library(plyr)
fun1<-function(){
    datehour<-paste(bidpx1$tradedate, #paste("20130724", "14")
                    substr(bidpx1$tradetime,1,2),sep="") 
    df<-cbind(datehour,bidpx1[,3:5]) #按列合并
    ddply(bidpx1,.(securityid,datehour),summarize,price = mean(bidpx1),size = sum(bidsize1)) 
}
head(fun1())
system.time(fun1()) #以system.time()查看fun1函数运行时间
file<-"fun1_rprof.out" #定义性能日志函数的输出文件位置
Rprof(file) #开始性能监控
fun1() #执行计算函数
Rprof(NULL) #停止执行监控,并输出文件
summaryRprof(file) #通过summaryRprof函数解析这个监控文件

可视化工具profvis

# install.packages("profvis")
library(profvis)
library(ggplot2)
p <- profvis({          
  data(diamonds, package = "ggplot2")           
  plot(price ~ carat, data = diamonds)          
  m <- lm(price ~ carat, data = diamonds)           
  abline(m, col = "red")            
})
htmlwidgets::saveWidget(p, "title.html") #可以保存到工作空间下html文件
本地生成的html文件
在console中 输出p结果

参考阅读:

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容