web-dev-qa-db-ja.com

Rのdata.tableパッケージのfreadの速度の背後にある理由

大きなデータファイルのdata.tablefread関数の速度に驚いていますが、どのようにしてこれほど高速に読み取ることができますか? freadread.csvの基本的な実装の違いは何ですか?

21
Vijay

colClassesnrowsなどの設定などの既知のアドバイスをすべて適用して_read.csv_と比較していると思います。他の引数なしのread.csv(filename)は、主に最初にすべてをcharacterであるかのようにメモリに読み込み、次に2番目のステップとしてそれをintegerまたはnumericに強制しようとします。

したがって、freadread.csv(filename, colClasses=, nrows=, etc) ..と比較します。

どちらもCで書かれているので、そうではありません。

特に理由は1つではありませんが、基本的に、freadメモリはファイルをメモリにマップし、ポインタを使用してファイルを反復処理します。一方、_read.csv_は、接続を介してファイルをバッファに読み込みます。

freadを_verbose=TRUE_と一緒に実行すると、それがどのように機能するかがわかり、各ステップで費やされた時間が報告されます。たとえば、列の種類をより正確に推測するために、ファイルの中央と末尾に直接スキップすることに注意してください(ただし、この場合は上位5つで十分です)。

_> fread("test.csv",verbose=TRUE)
Input contains no \n. Taking this to be a filename to open
File opened, filesize is 0.486 GB
File is opened and mapped ok
Detected eol as \n only (no \r afterwards), the UNIX and Mac standard.
Using line 30 to detect sep (the last non blank line in the first 'autostart') ... sep=','
Found 6 columns
First row with 6 fields occurs on line 1 (either column names or first row of data)
All the fields on line 1 are character fields. Treating as the column names.
Count of eol after first data row: 10000001
Subtracted 1 for last eol and any trailing empty lines, leaving 10000000 data rows
Type codes (   first 5 rows): 113431
Type codes (+ middle 5 rows): 113431
Type codes (+   last 5 rows): 113431
Type codes: 113431 (after applying colClasses and integer64)
Type codes: 113431 (after applying drop or select (if supplied)
Allocating 6 column slots (6 - 0 dropped)
Read 10000000 rows and 6 (of 6) columns from 0.486 GB file in 00:00:44
  13.420s ( 31%) Memory map (rerun may be quicker)
   0.000s (  0%) sep and header detection
   3.210s (  7%) Count rows (wc -l)
   0.000s (  0%) Column type detection (first, middle and last 5 rows)
   1.310s (  3%) Allocation of 10000000x6 result (xMB) in RAM
  25.580s ( 59%) Reading data
   0.000s (  0%) Allocation for type bumps (if any), including gc time if triggered
   0.000s (  0%) Coercing data already read in type bumps (if any)
   0.040s (  0%) Changing na.strings to NA
  43.560s        Total
_

注意:SSDのない非常に遅いネットブックでのこれらのタイミング。各ステップの絶対時間と相対時間は、マシンごとに大きく異なります。たとえば、もう一度freadを再実行すると、OSが前回の実行からキャッシュしたため、mmapまでの時間が大幅に短縮されることに気付く場合があります。

_$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                2
On-line CPU(s) list:   0,1
Thread(s) per core:    1
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             AuthenticAMD
CPU family:            20
Model:                 2
Stepping:              0
CPU MHz:               800.000         # i.e. my slow netbook
BogoMIPS:              1995.01
Virtualisation:        AMD-V
L1d cache:             32K
L1i cache:             32K
L2 cache:              512K
NUMA node0 CPU(s):     0,1
_
30
Matt Dowle