Bash Sed性能优化

Bash Sed性能优化,bash,sed,io,Bash,Sed,Io,我注意到,当我将sed与-I参数一起使用时,与将sed的输出重定向到一个全新的文件时相比,它使用的磁盘读/写资源要少得多,因此后者要快得多(至少在我的经验中是这样)。为什么会这样 以下是我使用的特定命令- sed -i '/\r/ s///g' file.txt <-- Slower one sed '/\r/ s///g' file.txt > file2.txt <-- Much faster one sed-i'/\r/s///g'file.txt

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

以下是我使用的特定命令-

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

sed-i'/\r/s///g'file.txt file2.txt我在Linux上用GNU sed 4.4测试了这一点,它应该与您的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会导致对同一文件进行115805次读/写:

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提交的行为与此相同

在解决这一问题之前,您可能希望使用重定向(或者更好的是,在本例中使用更合适的工具,如
tr


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

欢迎这样做,请务必在帖子中显示带有代码标记的输入和输出示例。这是哪个
sed
实现?在GNU-sed上,
strace
确认
-i
只是写入一个临时文件并交换这两个文件,而且它不缓冲,因此实际上比重定向慢。请注意,如果使用任何工具处理任何文件两次,第二次可能会快上千倍,因为文件在缓存中。@我在Cygwin上使用的另一个家伙。关于缓存,我也有同样的想法,所以我用两个不同的文件测试了我的假设,结果保持不变。你说
-I
使用更少的磁盘读/写,因此重定向速度更快。你的意思是相反的吗?我的意思是,当我查看任务管理器时,使用sed-I时的磁盘读/写MB/s值比使用重定向时低得多。我明白这有多误导。这个问题,所以任何GNU-sed版本在4.5之后(但不包括)都不应该有这个问题。