为什么 echo >file 比 echo 使用更实时?sed > 文件?

Pet*_*r.O 29 shell bash pipe echo time

下面的例子让我感到惊讶。这似乎是直觉......除了一个事实,即有一根胡须更有用户时间echo | sed组合。

为什么在单独运行时echo使用这么多sys 时间,或者问题应该是,如何sed改变游戏状态?似乎在这两种情况下echo都需要做相同的回声......

time echo -n a\ {1..1000000}\ c$'\n' >file

# real    0m9.481s
# user    0m5.304s
# sys     0m4.172s

time echo -n a\ {1..1000000}\ c$'\n' |sed s/^\ // >file

# real    0m5.955s
# user    0m5.488s
# sys     0m1.580s
Run Code Online (Sandbox Code Playgroud)

Gil*_*il' 30

bahamat 和 Alan Curry 说得对:这是由于您的 shell 缓冲echo. 具体来说,您的 shell 是 bash,它write每行发出一个系统调用。因此,第一个片段对磁盘文件进行了 1000000 次写入,而第二个片段对管道进行了 1000000 次写入,并且 sed(如果您有多个 CPU,则主要是并行的)由于其输出而对磁盘文件的写入次数要少得多缓冲。

您可以通过运行strace观察发生了什么。

$ strace -f -e write bash -c 'echo -n a\ {1..2}\ c$'\'\\n\'' >file'
write(1, "a 1 c\n", 6)                  = 6
write(1, " a 2 c\n", 7)                 = 7
$ strace -f -e write bash -c 'echo -n a\ {1..2}\ c$'\'\\n\'' | sed "s/^ //" >file'
Process 28052 attached
Process 28053 attached
Process 28051 suspended
[pid 28052] write(1, "a 1 c\n", 6)      = 6
[pid 28052] write(1, " a 2 c\n", 7)     = 7
Process 28051 resumed
Process 28052 detached
Process 28051 suspended
[pid 28053] write(1, "a 1 c\na 2 c\n", 12) = 12
Process 28051 resumed
Process 28053 detached
--- SIGCHLD (Child exited) @ 0 (0) ---
Run Code Online (Sandbox Code Playgroud)

echo即使是多行的,其他 shell(例如 ksh)也会缓冲输出,因此您不会看到太大的区别。

$ strace -f -e write ksh -c 'echo -n a\ {1..2}\ c$'\'\\n\'' >file'
write(1, "a 1 c\n a 2 c\n", 13)         = 13
$ strace -f -e write ksh -c 'echo -n a\ {1..2}\ c$'\'\\n\'' | sed "s/^ //" >file'
Process 28058 attached
[pid 28058] write(1, "a 1 c\n a 2 c\n", 13) = 13
Process 28058 detached
--- SIGCHLD (Child exited) @ 0 (0) ---
write(1, "a 1 c\na 2 c\n", 12)          = 12
Run Code Online (Sandbox Code Playgroud)

使用 bash 我得到类似的时间比。使用 ksh,我看到第二个代码段运行速度较慢。

ksh$ time echo -n a\ {1..1000000}\ c$'\n' >file

real    0m1.44s
user    0m1.28s
sys     0m0.06s
ksh$ time echo -n a\ {1..1000000}\ c$'\n' | sed "s/^ //" >file

real    0m2.38s
user    0m1.52s
sys     0m0.14s
Run Code Online (Sandbox Code Playgroud)