gpt4 book ai didi

R中data.table包中fread速度的原因

转载 作者:行者123 更新时间:2023-12-02 03:08:07 25 4
gpt4 key购买 nike

我对 fread 的速度感到惊讶函数位于 data.table对于大数据文件,但它是如何做到读取速度如此之快的呢? fread 之间的基本实现差异是什么?和read.csv

最佳答案

我假设我们正在与 read.csv 进行比较,并应用了所有已知的建议,例如设置 colClassesnrows 等。 read没有任何其他参数的 .csv(filename) 速度很慢,主要是因为它首先将所有内容读入内存,就好像它是字符,然后尝试将其强制为整数或第二步使用数字

因此,将 freadread.csv(filename, colClasses=, nrows=, etc) ...

它们都是用 C 语言编写的,所以不是这样的。

没有特别的原因,但本质上,fread 内存将文件映射到内存,然后使用指针迭代文件。而 read.csv 通过连接将文件读取到缓冲区中。

如果您使用 verbose=TRUE 运行 fread,它会告诉您它是如何工作的,并报告每个步骤所花费的时间。例如,请注意,它直接跳到文件的中间和末尾,以便更好地猜测列类型(尽管在本例中前 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,您可能会注意到 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

关于R中data.table包中fread速度的原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24424361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com