看板 R_Language 關於我們 聯絡資訊
效能諮詢(我想讓R 跑更快) [問題敘述]: 在function中引function, 主要是為了好讀好修. 可是這樣就很慢. 請問有什麼方式加速嗎? 例如引用的方法? [程式範例]: fun0 = function(fun){ x=1:10 y=10:1 fun1 = function(x,y){z=xy} fun2 = function(x,y){z=x*y} if(fun == "plus") z = fun1(x,y) else{ if(fun == "product") z = fun2(x,y) } return(z) } system.time(for(i in 1:1e7) fun0("product")) user system elapsed 12.70 0.00 12.72 # ----------------------------------------- for(i in 1:10) gc() fun0 = function(fun){ x=1:10 y=10:1 if(fun == "plus") z=xy else{ if(fun == "product") z=x*y } return(z) } system.time(for(i in 1:1e7) fun0("product")) user system elapsed 7.69 0.00 7.73 [環境敘述]: > sessionInfo() R version 3.4.4 (2018-03-15) Platform: x86_64-w64-mingw32/x64 (64-bit) Running under: Windows >= 8 x64 (build 9200) Matrix products: default locale: [1] LC_COLLATE=Chinese (Traditional)_Taiwan.950 LC_CTYPE=Chinese (Traditional)_Taiwan.950 [3] LC_MONETARY=Chinese (Traditional)_Taiwan.950 LC_NUMERIC=C [5] LC_TIME=Chinese (Traditional)_Taiwan.950 attached base packages: [1] stats graphics grDevices utils datasets methods base loaded via a namespace (and not attached): [1] compiler_3.4.4 tools_3.4.4 yaml_2.1.18 [關鍵字]: 選擇性,也許未來有用 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 213.47.170.138 ※ 文章網址: https://www.ptt.cc/bbs/R_Language/M.1522794834.A.96D.html
locka: 推,同樣也有這問題 04/04 11:22
obarisk: 做 profile 看看吧 04/04 12:11
celestialgod: 應該是每次都redefine fun1,fun2造成的overhead吧 04/04 16:41
celestialgod: 這種overhead在小量重複的時候不明顯,但是 04/04 16:42
celestialgod: 大量迴圈的時候這一點點差距就會顯得很大 04/04 16:42
celestialgod: https://goo.gl/1pKq3h 04/04 16:42
Edster: 我試過先定義function在全域變數, 結果一樣花1.7倍時間 04/04 18:38
Edster: 改了自己的code讓它比較好讀, 結果等到天荒地老. 04/04 18:40
Edster: 並不是redefine function的問題. 而是只要再引用就會這樣. 04/04 18:41
celestialgod: function call overhead 04/04 19:09
celestialgod: https://goo.gl/EaU9G2 04/04 19:10
Wush978: 可以用compiler::cmpfun加速,我測試過後,就一樣快了 04/04 21:57
Wush978: Hmm... 我加大replication後發現compiler::cmpfun沒有比 04/04 22:00
Wush978: 較快... 04/04 22:00
celestialgod: Wush我試過cmpfun了XDDD 04/04 22:01
Wush978: 不過你應該可以用function of function來避免redefine 04/04 22:02
Wush978: function 04/04 22:02
obarisk: 為什麼 function call 會讓 code 比較好讀? 04/04 22:32
obarisk: 改 pure function 都不會比較好讀了... 04/04 22:33
obarisk: 改一下 code style 並加上適當的註解比較合理 04/04 22:33
obarisk: myfun <- function(x, y, op) do.call(op, list(x, y)) 04/04 22:35
obarisk: myfun(1, 2, `+`) 04/04 22:35
obarisk: myfun(1, 2, `*`) 04/04 22:36
obarisk: 不曉得這樣的 code 有沒有比較清礎 04/04 22:36
obarisk: myfun <- function(x, y, op) op(x, y) 04/04 22:38
obarisk: 不用 do.call 04/04 22:39
celestialgod: 他那個應該只是舉例而已,fun1,fun2應該很長 04/04 23:04
obarisk: 我也只是舉例而已,概念上應該要寫這種 function 才有幫 04/04 23:48
obarisk: 助,要把變數參數化,否則兩個很長的 function 怎麼會比 04/04 23:48
obarisk: 較好讀 04/04 23:48