gpt4 book ai didi

bash - Sed 性能优化

转载 作者:行者123 更新时间:2023-12-05 05:15:36 25 4
gpt4 key购买 nike

我注意到当我将 sed 与 -i 参数一起使用时,它使用的磁盘读/写资源比我将 sed 的输出重定向到一个全新的文件时少得多,因此后者要快得多(至少根据我的经验).这是为什么?

这是我使用的具体命令 -

     sed -i '/\r/ s///g' file.txt <-- Slower one
sed '/\r/ s///g' file.txt > file2.txt <-- Much faster one

此外,我注意到当我对一个大小约为 35MB 的文件使用 sed 时,它能够在大约 0.3 秒内处理它(当我重定向而不是使用 -i arg 时)。但是,当我处理一个大约 7 倍大的文件时,操作大约需要 20 秒(再次使用重定向而不是 -i arg)。为什么是这样?这是否意味着 sed 在一堆较小的文件上比在一个大文件上运行得更快?当我有一个大小约为 25GB 的文件时,在使用 sed 处理之前拆分文件是否符合我的最佳利益?

最佳答案

我在使用 GNU sed 4.4 的 Linux 上对此进行了测试,它应该与您的 Cygwin 类似。 strace -o dump sed ... 显示每种情况下发生的情况:

通过重定向,缓冲输出导致 5MB 文件的 2498 次读/写:

openat(AT_FDCWD, "file.txt", O_RDONLY)  = 3
fstat(3, {st_mode=S_IFREG|0644, st_size=5213926, ...}) = 0
read(3, "The Project Gutenberg EBook of T"..., 4096) = 4096
fstat(1, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0
read(3, "\nBook 01 Genesis\r\n\r\n01:00"..., 4096) = 4096
write(1, "The Project Gutenberg EBook of T"..., 4096) = 4096
read(3, "wn image, in the image of God\r\n "..., 4096) = 4096
write(1, "002 And the earth was without fo"..., 4096) = 4096
read(3, "cattle, and to the fowl of the a"..., 4096) = 4096
write(1, "replenish the earth, and subdue "..., 4096) = 4096

使用 -i,无缓冲的 I/O 导致同一文件的 115,805 次读/写:

openat(AT_FDCWD, "file.txt", O_RDONLY)  = 3
openat(AT_FDCWD, "./sed6RccPF", O_RDWR|O_CREAT|O_EXCL, 0600) = 4
read(3, "The Project Gutenberg EBook of T"..., 4096) = 4096
write(4, "The Project Gutenberg EBook of T"..., 61) = 61
write(4, "of the King James Bible\n", 24) = 24
write(4, "\n", 1) = 1
write(4, "Copyright laws are changing all "..., 69) = 69
write(4, "copyright laws for your country "..., 69) = 69
write(4, "this or any other Project Gutenb"..., 43) = 43
write(4, "\n", 1) = 1

最新的 git commit 行为相同。

在解决此问题之前,您可能希望使用重定向(或者更好的是,在这种情况下使用更合适的工具,如 tr)。

sed 无论文件大小如何都以相同的速度处理,您看到的任何差异更可能是由于操作系统或驱动器的缓存所致。

关于bash - Sed 性能优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51446465/

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