5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[R] オブジェクトによる処理速度の違い

Last updated at Posted at 2014-05-26

世間的には常識なんだろうと思いますが、へぇ~と思ったのでメモ。
私はプログラミングをきちんとした形で学んだことがないので、こういう基礎的なところからして知識や配慮が欠如しています・・・。

R
x.null <- NULL   # 未定義、無値のオブジェクト(以下の代入によりベクトルになる)
system.time(for(i in 1:100000){x.null[i] <- i/100000})

x.1 <- numeric(1)   # 要素数 1 のベクトル(?)
system.time(for(i in 1:100000){x.1[i] <- i/100000})

x.vector <- numeric(100000)   # サイズを定義したベクトル
system.time(for(i in 1:100000){x.vector[i] <- i/100000})

x.matrix <- matrix(rep(0,100000),100000,1) # マトリクス
system.time(for(i in 1:100000){x.matrix[i,1] <- i/100000})

x.list <- list(numeric(100000))   # リスト
system.time(for(i in 1:100000){x.list[[1]][i] <- i/100000})

x.df <- data.frame(numeric(100000))   # データフレーム
system.time(for(i in 1:100000){x.df[i,1] <- i/100000})

library(data.table)   # データテーブル利用のためパッケージ読み込み

x.dt <- data.table(numeric(100000))   # データテーブル
system.time(for(i in 1:100000){x.dt[i,1] <- i/100000})

実行結果は以下の通り。(実行機はどこにでもあるような今時の安物 Windows PC)

# 未定義、無値のオブジェクト 
> system.time(for(i in 1:100000){x.null[i] <- i/100000})
   ユーザ   システム       経過  
      8.89       0.00       8.92 

# 要素数 1 のベクトル
> system.time(for(i in 1:100000){x.1[i] <- i/100000})
   ユーザ   システム       経過  
      8.91       0.00       9.00 

# サイズを定義したベクトル
> system.time(for(i in 1:100000){x.vector[i] <- i/100000})
   ユーザ   システム       経過  
      0.15       0.00       0.16 

# マトリクス
> system.time(for(i in 1:100000){x.matrix[i,1] <- i/100000})
   ユーザ   システム       経過  
      0.19       0.00       0.19 

# リスト
> system.time(for(i in 1:100000){x.list[[1]][i] <- i/100000})
   ユーザ   システム       経過  
      0.25       0.00       0.25 

# データフレーム
> system.time(for(i in 1:100000){x.df[i,1] <- i/100000})
   ユーザ   システム       経過  
     72.72       0.00      73.01 

# データテーブル
> system.time(for(i in 1:100000){x.dt[i,1] <- i/100000})
   ユーザ   システム       経過  
     47.02       0.00      47.20 

データフレーム・・・。笑。

ところでデータテーブルへの代入はこの書き方で行けましたが、要素の取り出しはリストみたいな書き方でないといけないみたいですね。

> x.dt[1,1]
[1] 1

> x.dt[[1]][1]
[1] 1e-05

まだよくわかってませんが。

とりあえずベクトル化できるものはできるだけ一旦ベクトルにして処理しようと思いました。

R
x.df <- data.frame(numeric(100000))
system.time({
   x.df.v1 <- as.numeric(x.df[,1])
   for(i in 1:100000){x.df.v1[i] <- i/100000}
   x.df[,1] <- x.df.v1
   rm(x.df.v1)
})
   ユーザ   システム       経過  
      0.16       0.00       0.16 
5
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?